问题
fun curry f x y = f (x, y);
fun uncurry f (x, y) = f x y;
fun compose (f, g) x = f (g x);
I understand compose function, but not quite understand curry and uncurry in ML. Can anyone explain these?
Also, what do the following two lines mean?
(1) compose (compose, uncurry compose)
(2) compose (uncurry compose, compose)
回答1:
If you look at the types, then you will clearly see what curry
and uncurry
does.
Remember that it is possible to define function which either takes its arguments as one big tuple, or as multiple arguments (in reality it becomes a "chain" of functions each taking 1 argument, see this wiki):
fun foo (a,x) = a*x+10
fun bar a x = a*x+20
The difference is clearly seen in their types:
val foo = fn : int * int -> int
val bar = fn : int -> int -> int
The curry
function "transforms" a function that takes its arguments as a tuple, into a "chain" of functions that each takes 1 of the arguments. This is specifically handy when we want to compose a series of functions where some of them have been partially applied with arguments. See how the type of foo
is changed:
- curry foo;
val it = fn : int -> int -> int
Now we can try and compose the two functions:
- (curry foo 5 o bar 1) 4;
val it = 130 : int
First 4 is applied to bar 1
as the argument x
, then the result of that computation (bar 1 4
) is given as the x
argument to foo
.
Obviously uncurry
is used for the reverse process:
- uncurry bar;
val it = fn : int * int -> int
来源:https://stackoverflow.com/questions/8395564/what-are-curry-and-uncurry-in-high-order-functions-in-ml