Skip to content
Search

Scala:Currying

lastmod 2021-08-06created 2019-01-228 edits

Currying was named by Christopher Strachey in 1967 after Haskell Brooks Curry.

Currying is a technique where, when a function with multiple arguments is called with fewer parameters than it has, it takes the missing parameters as arguments.

About

A method can define multiple parameter lists. When a method is called with fewer parameter lists than it has, it produces a new function that takes the missing parameter lists as arguments.

For example, defining multiple parameter lists, as in def modN(n: Int)(x: Int)= ((x % n) == 0).

Example

A method can define multiple parameter lists. When a method is called with fewer parameter lists than it has, it produces a new function that takes the missing parameter lists as arguments.

Consider the following example.

object CurryTest extends App {

  def filter(xs: List[Int], p: Int => Boolean): List[Int] =
    if (xs.isEmpty) xs
    else if (p(xs.head)) xs.head :: filter(xs.tail, p)
    else filter(xs.tail, p)

  def modN(n: Int)(x: Int) = ((x % n) == 0)

  val nums = List(1, 2, 3, 4, 5, 6, 7, 8)
  println(filter(nums, modN(2)))
  println(filter(nums, modN(3)))
}

Note: the modN method is partially applied in the two filter calls. That is, only its first argument is actually applied. The expression modN(2) produces a function of type Int => Boolean, so it can be used as the second argument of the filter function.

Here is the output of the program above.

List(2,4,6,8)
List(3,6)

See also

Favorite site

author Zer0 sitemap