Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

Curried functions

This feature is very popular in function languages like Haskell. Curried functions are similar to partial applications, because they allow some arguments to pass now and others later. However, they are a little bit different.

Curried functions - Scala REPL

Following is an example using curried function in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>// Function Definition

scala>def sum(x:Int)(y:Int):Int = x+y

sum: (x: Int)(y: Int)Int

scala>

scala>// Function call - Calling a curried function scala>sum(2)(3) res0: Int = 5

scala>

scala>// Doing partial with Curried functions scala>val add3 = sum(3) _ add3: Int => Int = scala>

scala>// Supply the last argument now scala>add3(3) res1: Int = 6 scala>

For the preceding code, we create a curried function in the function definition. Scala allows us to transform regular/normal functions into curried functions. The following code shows the usage of the curried function.

Curried transformation in Scala REPL

Following is an example using curried transformation in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>def normalSum(x:Int,y:Int):Int=x+y

normalSum: (x: Int, y: Int)Int

scala>

scala>val curriedSum = (normalSum _).curried curriedSum: Int => (Int => Int) = scala>

scala>val add3= curriedSum(3) add3: Int => Int = scala>

scala>println(add3(3))

6

scala>

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics