Curried and partial functions in Scala
Haskell Curry and curried functions
Haskell Curry (1900-1982) was a mathematician. He worked on combinatory logic, a topic in mathematics. Combinatory logic became a basis for functional programming languages.

From Wikipedia:

Functional programming treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Haskell is an example of a functional programming language. It was named 'haskell' after Haskell Curry's first name. The term currying or curried comes from his last name.

An example of curried function (Scala):

private def multiplyCurried(a: Int)(b: Int) = a * b

Notice separate argument lists:

(a: Int)
(b: Int)

Curried function can be used as a partially applied function (do not confuse with partial functions ):

val multiplyBy2 = multiplyCurried(2) _

Notice data type of multiplyBy2:


It's an anonymous function created by binding a value to first argument.
What you get back is a function that takes one less argument. An example:

println(multiplyBy2(3)) //prints 6

Here is a more useful example:

private def processLines[A](fileName: String)(f: (Seq[String]) => A): A = {
	val input = Source.fromFile(fileName)
	try {
		val output = ListBuffer.empty[String]
		input.getLines.foreach(output+=) f(output)
	} finally {
		Option(input) foreach (_.close())

And test usage:

val useLines = processLines[Seq[String]]("properties.txt") _
val linesWithNumbers = useLines { lines => { t => "line: %d, text: %s".format(t._2, t._1) } }

val lineLengths = useLines( => "line length: %d".format(line.length())))

Once curried function is partially applied it can be passed around as a function with limited parameter list.

Curried functions can be great for code reuse (function can be bound to input data that is computed once and processed in different ways) or parallel processing (partially applied function can be further processed in separate threads).

Curried functions can also help with specialization. For example:

private def customFilter(findOdd: Boolean)(number: Int): Boolean = if (findOdd) number % 2 != 0 else number % 2 == 0

val numbers = Seq(1, 2, 3, 4, 5)
val evenFilter = customFilter(false)_
val oddFilter = customFilter(true)_


Sequence filter function expects:

f:(x) => Boolean

Partially applied functions evenFilter and oddFilter can provide that interface from curried function customFilter .

For explanation of partial functions (functions that are defined for a limited set of input arguments) see this blog post:
Scala partial functions (without a PhD)