Currying in Scala
Currying is a functional Paradigm that allows us to take a function that has multiple arguments and change it into a sequence of functions that only takes one argument. This is useful when it comes to the segregation of duties principle in programming where each function does one thing only even with disparate arguments. It also makes it easier to use high order functions that can be provided as arguments.
Let us take a function that takes two args f(x,y) now with currying we will create f(x) and g(y) which together will yield the result of f(x,y).
Let us look at a concrete example. Say for example you want to calculate the slope of a straight line. For this you need two x,y coordinates your startPoint and the endPoint. to make life simpler I have wrapped the x and y in a simple Point class like this
class Point(val x: Int, val y: Int){}
Now we can create the currying function that takes two arguments or two Point classes.
def slope(p: Point)(q: Point) = {
//(Int,Int) => Unit on both args
val s=(q.y-p.y)/(q.x-p.x)
println("Slope= "+s)
}
now we can call the slope function as follows
//curry slope only giving first arg then change the function name to startPoint
val startPoint = slope (p) _
Note how after the call we have the underscore. This denotes that something is missing and will be provided later which indicates partial application of a function.
At this point is important to realise we have changed the slope function into another function called startPoint that takes 1 argument which is a Point class. So lets create some Point classes and call the startPoint function
val p = new Point(2,2)
val q = new Point(3,3)
val z = new Point(3,25)
//now fill in second arg to complete the _ on partial above
startPoint (q)
startPoint (z)
Now you will see we have called the startPoint with only one argument but we have the slope function which was not executed until the second argument was given to the curried function.
This fulfils the contract that a curried function is a function that takes multiple arguments as function slope did and then changed it to a sequence of functions called startPoint and we only needed to provide one argument to each function.
People who enjoyed this article also enjoyed the following:
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
And the following Trails:
C++Java
python
Scala
Investment Banking tutorials
HOME
