Tuesday, 19 December 2017

Introduction to Scala - VI

In this post, we will look at the concept of  Currying in Scala. For all the work in this post, we will use Read-Evaluate-Print-Loop Scala interpreter. Some familiarity with Java will be of great help in understanding Scala.

Let us first define a simple function and run it as shown below:

def product(x: Int,y: Int) = x * y

product(2,4)

The results are shown below:

scala> def product(x: Int,y: Int) = x * y
product: (x: Int, y: Int)Int

scala> product(2,4)
res12: Int = 8


The same function can be rewritten as a curried function taking single arguments multiple times as shown below:

def ProductCurrying(x: Int)(y: Int) = x * y

ProductCurrying(2)(4)

The results are shown below:

scala> def ProductCurrying(x: Int)(y: Int) = x * y
ProductCurrying: (x: Int)(y: Int)Int

scala> ProductCurrying(2)(4)
res13: Int = 8
 

A way to pass arguments one by one is shown below:

val interim = ProductCurrying(2) _

interim(4)

The results are shown below:

scala> val interim = ProductCurrying(2) _
interim: Int => Int = <function1>

scala> interim(4)
res17: Int = 8


The underscore indicates the blank argument.

ProductCurrying curried function can be rewritten as shown below:

def ProductCurrying1(x: Int) = (y: Int) => x * y

Then, we can pass the parameters one by one as shown below:

val interim = ProductCurrying1(2)
interim(4)


The results are shown below:

scala> def ProductCurrying1(x: Int) = (y: Int) => x * y
ProductCurrying1: (x: Int)Int => Int

scala> val interim = ProductCurrying1(2)
interim: Int => Int = <function1>

scala> interim(4)
res15: Int = 8


Defining a function with three arguments and then called to confirm is shown below:

def ProductCurrying2(x: Int) = (y: Int) => (z: Int) => x * y * z

ProductCurrying2(2)(4)(5)

The results are shown below:

scala> def ProductCurrying2(x: Int) = (y: Int) => (z: Int) => x * y * z
ProductCurrying2: (x: Int)Int => (Int => Int)

scala> ProductCurrying2(2)(4)(5)
res22: Int = 40


This concludes the discussion on Currying in Scala.