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:

package test

object PartiallyAppliedFunctionsTest {

def main(args : Array[String]) {

val partiallyAppliedFunctions = new PartiallyAppliedFunctions();

println("sum 4 arg 1 + 2 + 3 + 4 = " + partiallyAppliedFunctions.getSum4arg()(1, 2, 3, 4)) // expect 10

println("partiallyAppliedFunction 3 arg, 1 + 2 + 3 = " + partiallyAppliedFunctions.getSum3arg()(1, 2, 3)) // expect 6

println("partiallyAppliedFunction 2 arg, 1 + 2 = " + partiallyAppliedFunctions.getSum2arg()(1, 2)) // expect 3
}
}

class PartiallyAppliedFunctions() {

private def sum(i1 : Int, i2 : Int, i3 : Int, i4 : Int) = {

i1 + i2 + i3 + i4
}

def getSum4arg() = {

sum _
}

def getSum3arg() : (Int, Int, Int) => Int = {

sum(0, _ : Int, _ : Int, _ : Int)
}

def getSum2arg() : (Int, Int) => Int = {

sum(0, 0, _ : Int, _ : Int)
}
}
The above example shows the function _ syntax to reference a function as a value.

Also, functions getSum3arg() and getSum4arg() show the use of partial functions to re-use an existing function by partially defining and supplying some of the arguments.


.

No comments: