Curried Functions
Currying and curried functions are named after Haskell B. Curry, although he attributed the technique to Schonfinkel (Curry, 1980) so maybe it should be called Schonfinkelling.
Currying applies to functions of two or more parameters. The use of a curried function generally needs fewer characters, especially `,', `(' and `)', than does the use of the uncurried version.
Most functional programming (FP) languages support curried functions. There is no reason why imperative languages cannot do so, but most do not.
uncurried | curried | |
---|---|---|
e.g. type | plus_{u} :Int×Int->Int | plus_{c} :Int->Int->Int |
defn | plus_{u}(x,y) = x+y | plus_{c} x y = x+y |
use | plus_{u}(1,2) returns 3 | plus_{c} 1 2 returns 3 |
use |
successor x = plus_{u}(1,x) successor 7 returns 8 |
successor = plus_{c} 1 successor 7 returns 8 |
Note that plus_{c} 1 is well defined but plus_{u}(1, ?) is not. Strictly, plus_{u} is a function of one parameter, that parameter being a pair of integers, but we often say that plus_{u} has two parameters. And strictly, plus_{c} is a function of one parameter which returns a function of one parameter, but we often say that plus_{c} has two parameters.
Parentheses
- Parentheses are sometimes necessary, even with curried functions, e.g.
- f_{c} a (b c) differs from f_{c} (a b) c
- In mathematics, functions of one parameter do not need parentheses except sometimes to direct the parsing of an expression. Just as
- (p+q)*r differs from p+q*r = p+(q*r)
- so
- f g h = (f g) h differs from f(g h) = f(g(h))
- After all x = (x), so surely
- f(x) = f x
- However, many programming languages have not woken up to this and still require `( )', even for f(x).
Currying
- Every uncurried function can be curried and every curried function can be uncurried. Given
- curry : (t×u -> v) -> t -> u -> v
- curry f_{u} x y = f_{u}(x,y)
- and
- uncurry : (t->u->v) -> t×u -> v
- uncurry f_{c} (x,y) = f_{c} x y
- then
- plus_{u} = uncurry plus_{c}
- plus_{c} = curry plus_{u}
- Note that with these definitions, curry and uncurry are curried functions!
- (You can define curry3 and uncurry3 for functions of three parameters, and so on.)
uncurried | curried | |
---|---|---|
e.g. type | map_{u} : ((t->u) × List t) -> List u | map_{c} : (t->u) -> List t -> List u |
defn |
map_{u}(f, nil) = nil map_{u}(f, cons_{u}(x,xs)) = cons_{u}((f x), (map_{u}(f, xs))) |
map_{c} f nil = nil map_{c} f (cons_{c} x xs) = cons_{c} (f x) (map f xs) |
where cons_{u} and cons_{c} are the uncurried and curried list constructors respectively. | ||
use | map_{u}(sqr, [1,2,3]) = [1,4,9] | map_{c} sqr [1,2,3] = [1,4,9] |
where [1,2,3] is shorthand for cons_{u}(1, cons_{u}(2, cons_{u}(3, nil))) or for cons_{c} 1 (cons_{c} 2 (cons_{c} 3 nil)) as appropriate. |