My mostly technical blog. An on-line journal of my activity in the IT industry and any other technical interests or techy things that happen to catch my attention.

Friday, 2 January 2009

Scala, placeholders and partial functions

A couple of Scala examples to demonstrate the use of place-holder syntax and partial functions. These two things are related but partial functions goes beyond syntactical conciseness to provide new and powerful constructions.

Substitution:

package test

object Placeholders {

def main(args : Array[String]) {

val myNumbers = 1 to 10 //List(1, 2, 3, 4, 5, 6, 7, 8, 9);

println("Greater than 3")

var result = myNumbers.filter((x : Int) => x > 3)

result.foreach(println) // result.foreach((x) => println(x))

println("Greater than 4")

result = myNumbers.filter(x => x > 4)

result.foreach(println)

println("Greater than 5")

result = myNumbers.filter(_ > 5) // _ placeholder _ for

result.foreach(println) }}

Partially applied functions:

Partial functions are functions defined with only some of the arguments (or none), as the following example demonstrates: