Working with Functions in Scala – Part 1

Scala treats functions as first class citizens. I keep forgetting the syntax for it, so putting it here as a handy reference. This post deals with the following features of Scala:

  1. Anonymous Functions
  2. Assigning Functions to variables
  3. Composite Functions
    Please note that the term ‘function’ here is used to refer to both mathematical functions and programmatic functions. The key strength of Functional Programming languages is the ability to unify both.

Anonymous Functions

Let’s look at a regular function first. We can define a function f which takes an Integer argument and gives an Integer result as follows:

def f(x:Int) = x+2                     

Nothing surprising there. Now, lets look at the syntax for an anonymous function. An anonymous function in Scala is defined as follows:

(x:Int)=>(x+2):Int

We can omit the type for the result, which thus gives us:

(x:Int)=>x+2

But we can’t omit the type for the parameter, i.e.:

(x)=>x+2 //Doesn’t compile

Now that we’ve created an anonymous function, we can pass a variable to it and get a result. For this, we enclose the entire anonymous function definition in parentheses and pass the argument in another set of parentheses. Passing 3 to the anonymous function below gives us 5 as expected

((x:Int)=>(x+2))(3)               > res3: Int = 5

 

Assigning Functions

If we want to reuse the function again and again, we need to assign it to a variable. So, let’s do that. Using an immutable variable declaration:

val f = (x:Int)=>(x+2)            //Omitting the type declaration of the result

You can use ‘var’ instead of ‘val’ if you require a mutable variable. ‘val’ in Scala is similar to final in Java

So, now we can pass an argument to the function as follows:

f(3)                                      //> res4: Int = 5

And it works as expected!

 

Composite Functions

So, let’s take this a bit further then. Suppose we want to pass this function as an argument to another function. This is similar to composite functions in mathematics i.e., consider the following functions for example:

f(x) = x+3

g(x) = x*2

g o f = g[f(x)] = (x+3)*2

So, if we pass 3 to the composite function, we expect 10 as the result

g o f(3) = g[f(3)] = g(5) = 5*2 = 10

Let’s see how we can do this in Scala. Unfortunately, we cannot simply pass one function as the argument to another function. I know it would be simply awesome if we could do:

g(f)       //Doesn’t compile!

Unfortunately, that doesn’t work. But the good news is, there is a reasonable alternative which is not bad in terms of readability. If we translate this to plain English, we’d say “g circle f of x means first calculate f(x) and then calculate g(x)”

You probably guessed it, the method that makes this possible is andThen

Here’s how it’s done in Scala:

val f = (x:Int)=>x+2

val g = (x:Int)=>x*2

val comp = (f andThen g)

And you can build on this ad infinitum like:

(f andThen g andThen h andThen … )

So, if we pass 3 to comp, we get 10 as expected:

comp(3)                                   //> res5: Int = 10

Of course standard rules of anonymous functions apply. We can just calculate the value of the composite function without having to declare it:

(f andThen g)(3)                          //> res6: Int = 10

 

And that’s a quick overview of anonymous functions and assigning functions. Of course, a function can have any number of variables and it can be used in exactly the same way as given above.

We take functions a bit further in Part-2 which can be found here: Working with Functions in Scala – Part 2

Advertisements

2 thoughts on “Working with Functions in Scala – Part 1

  1. Pingback: Working with Functions in Scala – Part 2 « Emptiness in void

  2. Hello there! This blog post could not be written
    any better! Going through this post reminds me of my
    previous roommate! He continually kept preaching about this.
    I will forward this information to him. Fairly certain he’s going to have a good read. Thank you for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s