Curried functions in Scala

This is a functional programming concept.
The simplest form of the idea is this – imagine a function with 2 parameters, x and y and providing a sister-function to it where one of the parameters is set, this is similar to how the curried functions work. My focus in this example is the syntax.

 * Example of 'curried' method on functions.
 *  Having function f(x:X,y:Y):Z f.curried returns function g(x:X) returning (y:Y) => Z
object CurriedFunction extends App {
  /* We will provide a 'charAt' function taking a String and position (Int). */
  val f: (String,Int) => Char = (s,i) => s.charAt(i)

  /* Currying the method - we now create a function g taking just an Int. */
  val g = f.curried("test")

  /* Another form - but h takes 2 parameter lists - both containing one element. */
  val h = f.curried
  /* How we call the 2 curried methods. */
  println("Value for test, 1 = " + g(1))
  println("Value for diddle, 1 = " + h("diddle")(1))

The real purpose of currying is to do with arity – turning a function with multiple arguments into a series of functions with single arguments, but it involves functions returning other functions…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s