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 | plusu :Int×Int->Int | plusc :Int->Int->Int |
defn | plusu(x,y) = x+y | plusc x y = x+y |
use | plusu(1,2) returns 3 | plusc 1 2 returns 3 |
use |
successor x = plusu(1,x) successor 7 returns 8 |
successor = plusc 1 successor 7 returns 8 |
Note that plusc 1 is well defined but plusu(1, ?) is not. Strictly, plusu is a function of one parameter, that parameter being a pair of integers, but we often say that plusu has two parameters. And strictly, plusc is a function of one parameter which returns a function of one parameter, but we often say that plusc has two parameters.
Parentheses
- Parentheses are sometimes necessary, even with curried functions, e.g.
- fc a (b c) differs from fc (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 fu x y = fu(x,y)
- and
- uncurry : (t->u->v) -> t×u -> v
- uncurry fc (x,y) = fc x y
- then
- plusu = uncurry plusc
- plusc = curry plusu
- 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 | mapu : ((t->u) × List t) -> List u | mapc : (t->u) -> List t -> List u |
defn |
mapu(f, nil) = nil mapu(f, consu(x,xs)) = consu((f x), (mapu(f, xs))) |
mapc f nil = nil mapc f (consc x xs) = consc (f x) (map f xs) |
where consu and consc are the uncurried and curried list constructors respectively. | ||
use | mapu(sqr, [1,2,3]) = [1,4,9] | mapc sqr [1,2,3] = [1,4,9] |
where [1,2,3] is shorthand for consu(1, consu(2, consu(3, nil))) or for consc 1 (consc 2 (consc 3 nil)) as appropriate. |