ocaml - 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?
解决方案
有时在转向通用案例之前尝试一些示例会更容易。例如,在 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)
右侧看起来非常相似:它们的区别仅在于在两个参数上调用的函数的名称。如果我们想概括这两个函数,一种解决方案是提供该函数mult
或add
作为新函数的参数。我们暂时称它为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
下一步是注释x
andy
出现在 and 的新定义的右侧和左侧的相同位置mult2
,add2
这意味着我们可以省略它们
let mult2 = f mult
let add2 = f add
这意味着我们的函数f
将一个接受一对参数的函数转换为一个接受两个参数的柯里化函数。换句话说,f
可以更好地称为curry2
:
let curry2 f x y = f (x,y)
后续练习可能是尝试编写一个curry3
或一个uncurry2
函数。
推荐阅读
- python - Numpy 创建一个空的 alpha 图像
- javascript - 根据日期+持续时间(分钟)对数组(甘特计划)进行排序 - 带有静态中断(日期+持续时间)
- xpath - XQuery - 地图合并问题 - 执行 xbase
- android - 关闭所有意图并关闭应用程序
- python - 如何保存神经网络模型的所有细节?
- javascript - 错误:SyntaxError:无法在模块 JavaScript 之外使用 import 语句
- java - Android Studio - 如何显示 java 字节码?
- c# - 无序执行是 .Net Core 应用程序中并发线程的常见问题吗?
- css - 为什么蓝色不加起来?
- c# - 在 Angular 和 .Net Core API 中显示自定义服务器端错误消息