Thursday, June 26, 2008

scala functional programming

i continued learning scala reading the 'Scala By Example' tutorial from the website. next up was functional programming in scala. in scala functions are first class citizens. that means you can declare functions and pass them around as parameters or return them from other functions. let's first see, how to define a function:

def plus1(a : Int) : Int = 1 + a

it takes an argument a of type Int and returns 1 + a (you guessed it). you can call this function like plus1(2). [you could have enclosed the body of the function in curly braces, but it's just one expression, so you don't have to]

so, now let's define a higher-order function. that's a function which takes another function as parameter or returns a function.

def doWithInt(a : Int, f : Int => Int) : Int = f(a)

this is a function that takes an Int as first parameter and a function type as second. the parameter f is a function of type Int => Int which takes an Int as parameter and returns an Int. this function simply applies the function f to the parameter a. you could call this function passing to it a reference to the function plus1 declared before: doWithInt(3, plus1). this will return 4 as it applies plus1 to 3.

so, these are just the basics of functional programming with scala. things can become quite weird when it comes to more complex higher-order functions, e.g. function returning functions, currying or recursion. have a look at 'Scala By Example' for examples.

one thing i forgot to mentioned is some syntactic sugar for the example above. instead of calling doWithInt(3, plus1) you could have equally done

doWithInt(3, 1 +)

this is because + is a member function of the type Int, as seen in a previous post.

so, that's it for this post then. more on functional programming with scala coming soon.

No comments: