Monday 25 August 2014

Scala Note 19: Function Currying

1. Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.

2. Currying is the technique of transforming "a function that takes multiple arguments" into a function that takes a single argument (the other arguments having been specified by the curry).


3. The single argument is the value of the first argument from the original function and the function returns another single argument function. This in turn would take the second original argument and itself return another single argument function. 

This chaining continues over the number of arguments of the original. The last in the chain will have access to all of the arguments and so can do whatever it needs to do.

Currying in Scala allows us to defer execution and reuse functions.


scala> val sum = (a: Int) => (b: Int) => a + b
sum: Int => Int => Int = <function1>

scala> sum(3)(5)
res2: Int = 8
So without having access to a syntax that lets you define a function of two arguments, you just basically achieve that with a function sum taking an argument a returning a function equivalent to adda that takes a argumentb and returns a + b. And that's called currying.


Another example:

def sum(f: Int => Int)(a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sum(f)(a + 1, b)

sum(x => x * x)(1, 10) is equivalent to the following expression:
(sum(x => x * x))(1, 10).

the function sum is applied to the squaring function (x => x * x). Function application associates to the left. The resulting function is then applied to the second argument list, (1, 10).


Reference:

http://stackoverflow.com/questions/17768686/currying-example-in-scala



No comments:

Post a Comment