Saturday, December 24, 2016

Exploring Currying and Partial Application using Scala

tl;dr

  1. Currying is different from Partial (Function) Application.
  2. In Scala, it is possible to define a function that returns another function which can be called with arguments. Although this might look similar, it is not necessarily the same thing as either Currying or Partial (Function) Application.
  3. What is currying? It is a process whereby the multiple arguments required by a function are passed in, one at a time, instead of the typical process of calling the function by supplying all its arguments at once.

    val volume = 
    (length: Double, breadth:Double, height: Double) => 
                                     length * breadth * height
    
    // called with the required argument at once
    volume(1,2,3) 
    
    // creates a curried version of the function
    val curriedVersion = volume.curried
    
    // with the curried version we can pass in the arguments 
    // one after the other
    
    // pass first argument
    val withFirstArg = curriedVersion(1) 
    
    // and now with second argument
    val withFirstArgAndSecondArg = withFirstArg(2)
    
    // and now with third argument which yields the result
    val volumeValue: Double = withFirstArgAndSecondArg(3) 
    
    
  4. Partial Application what is it? It is possible to take a function that expects multiple arguments and pre-fill some of these arguments. Doing this, returns a function that can then be called by supplying the remaining argument(s) that were not pre-filled.

    val volume = 
    (length: Double, breadth:Double, height: Double) => 
                                     length * breadth * height
    
    // called with the required argument at once
    volume(1,2,3)
    
    // first and second argument pre-filled
    val withFirstAndSecondArgsSet: (Double) => Double = volume(1,2,_)
    
    // now third argument is supplied and result evaluated
    val volumeValue: Double = withFirstAndSecondArgsSet(3)
     
    
  5. Currying can then be seen as a specialised outcome of Partial Application. The resulting function of Partial Application can have any number of arguments. With Currying it has to be a chained sequence of functions that take one argument at a time.
  6. Currying can also be seen as a sequence of Partial Application where each step involves partially applying only one of all possible arguments defined by the function.
  7. Partial (Function) Application is different from partial functions.