问题描述
fun curry f x y = f (x, y);
fun uncurry f (x, y) = f x y;
fun compose (f, g) x = f (g x);
我了解撰写功能,但不太了解ML中的咖喱和粗俗用法.谁能解释这些?
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)
推荐答案
如果查看类型,那么您将清楚地看到curry
和uncurry
的作用.
If you look at the types, then you will clearly see what curry
and uncurry
does.
请记住,可以定义将其参数作为一个大元组或多个参数的函数(实际上,它成为每个带有1个参数的函数的链",请参见此 wiki ):
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
curry
函数将以其元组作为参数的函数转换"为一个函数链,每个函数均采用1个参数.当我们要组成一系列函数,其中一些函数已部分应用参数时,这特别方便.查看如何更改foo
的类型:
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
首先将4作为参数x
应用于bar 1
,然后将计算结果(bar 1 4
)作为x
参数作为foo
.
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
.
很明显,uncurry
用于反向过程:
Obviously uncurry
is used for the reverse process:
- uncurry bar;
val it = fn : int * int -> int
这篇关于ML中高阶函数中的咖喱和无咖喱是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!