在 OCaml 中展开元组
有没有办法将函数作为函数参数应用于元组成员?或者如果没有,我是否可以创建一个具有任意数量参数的函数,并在其主体中将另一个函数应用于“尾部”,因为它将是其参数?
Is there any way to apply function to tuple members as function arguments? Or if not, can I anyhow create a function with arbitrary number of arguments and in its body apply some another function to the "tail" as it would be its arguments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般情况下,不会。对于 2 个参数的情况,您可以使用 Pervasives 的电池扩展。
也许可以使用
Obj
模块来编写一些东西,就像printf
的内部所做的那样,但我会远离它。困难在于类型系统没有为您提供表达广义 curry 或 uncurry 函数类型的方法。类型系统不允许您“计算”元组的长度 - 2 元组就是 2 元组,您没有办法表达(a*b*c)
实际上是带有附加组件的(a*b)
。 printf 具有编译器的特殊支持,可以使类型正常工作,并且它会导致函数类型成为格式类型的一部分(因此类似的解决方案不适用于元组)。In the general case, no. For the case of 2 arguments, you can use the
curry
anduncurry
functions in the Batteries extensions to Pervasives.It might be possible to cook something up with the
Obj
module, like the internals ofprintf
do, but I would stay far far away from that. The difficulty is that the type system does not give you a way to express the type of a generalizedcurry
oruncurry
function. The type system does not let you "compute" over the length of a tuple - a 2-tuple is a 2-tuple and you don't have a way to express that(a*b*c)
is really(a*b)
with an additional component.printf
has special support from the compiler to make the types work out properly, and it results in the function type being a part of the format type (so similar solutions won't work for tuples).该语言本身不允许您在任意大小的元组上定义函数。
然而,可以通过遵循这种折叠技术来定义具有任意数量参数的函数(它是针对 SML 进行描述的,但是在 OCaml 中同样有效)。
The language itself does not allow you to define a function on tuples of arbitrary size.
It is however possible to define functions with an arbitrary number of arguments by following this folding technique (it's described there for SML but works equally well in OCaml).