Functional Programming explained to my grandma
Anne-Honyme
13.7K views
Currying
Currying is one of the words you will hear the most when you start to work with functional programming. It is also one of the hardest to figure out.
- Definition: Currying is the technique of translating the evaluation of a function which takes multiple arguments into evaluating a sequence of functions, each with a single argument *
We can see currying as a series of partial application.
For a function who has N parameters, a partial application will have N-X. It improves code readability by binding some parameters and giving names to specific uses.
Implement the area computation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package example
/**
* Created by charlotte on 15/06/17.
*/
object Area {
def area(x : Double, y:Double):Double =(x, y) match { // it's pattern matching
// you can use it to define some differents implementations
// as a function of the parameters
case (_, math.Pi) => x*x*math.Pi // for example here you can define a specific implementation for circles
case (_, _) if x>0 && y>0 => y*x //and another one for rectangle
}
def circleArea(radius: Double): Double= ??? //TODO Compute the circle area using the existing method
def squareArea(side: Double): Double= ??? //TODO Compute the square area using the existing method
//let's create circleArea and squareArea from the area function
}
Now we have seen what is partial application, we can introduce currying as a series of partial application, where at each step we only apply one parameter.
Implement the multiply and multiplyByTwo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package example
/**
* Created by charlotte on 13/05/17.
*/
object CurryingObject {
def multiply(x : Int, y: Int):Int= x*y //TODO define a function who multiply x by y
def multiplyByTwo(x:Int) = ??? //TODO define a function who multiply x by y
}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds