首页 > 解决方案 > Function which make uncurried curried(not using ramda library)

问题描述

I'm a beginner of Ocaml and I want to make uncurried function curried.

for example,

let add (x,y) = x + y

It is an uncurried form and I want to make a function called "curry" like

let inc = curry(add)(1)
let ret = inc(2)

If we apply my own "curry", it can be partially applied.

Since I'm the first time in Ocaml, I just thought extract entries from the tuple in the add function(quite silly...) like

let get_1_2 (a,_) = a
let get_2_2 (_,a) = a

let curry f tp = function
    f (get_1_2 tp) (get_2_2 tp)

But I know it does not make sense at all...
So How can I start?

标签: ocaml

解决方案


有时在转向通用案例之前尝试一些示例会更容易。例如,在 add 函数的情况下,您从

let add (x,y) = x + y

你想去

let add2 x y = x + y

在这种情况下,您可以看到新 curried 函数的右侧与旧 add 函数的右侧相同。因此,您可以将 curried 函数重写为

let add2 x y = add (x,y)

如果你转向乘法,我们可以从

let mult (x,y) = x * y

let mult2 x y = mult (x,y)

现在如果你比较我们的两个咖喱函数

let mult2 x y = mult (x,y)
let  add2 x y  =  add (x,y)

右侧看起来非常相似:它们的区别仅在于在两个参数上调用的函数的名称。如果我们想概括这两个函数,一种解决方案是提供该函数multadd作为新函数的参数。我们暂时称它为f

 let f mult_or_add x y = mult_or_add(x,y)

mult2然后我们可以改写add2

let mult2 x y = f mult x y
let  add2 x y = f  add x y

下一步是注释xandy出现在 and 的新定义的右侧和左侧的相同位置mult2add2这意味着我们可以省略它们

let mult2 = f mult
let  add2 = f  add

这意味着我们的函数f将一个接受一对参数的函数转换为一个接受两个参数的柯里化函数。换句话说,f可以更好地称为curry2

let curry2 f x y = f (x,y)

后续练习可能是尝试编写一个curry3或一个uncurry2函数。


推荐阅读