在 OCaml 中展开元组

发布于 2024-10-08 13:30:28 字数 86 浏览 0 评论 0原文

有没有办法将函数作为函数参数应用于元组成员?或者如果没有,我是否可以创建一个具有任意数量参数的函数,并在其主体中将另一个函数应用于“尾部”,因为它将是其参数?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨巷深深 2024-10-15 13:30:28

一般情况下,不会。对于 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 and uncurry functions in the Batteries extensions to Pervasives.

It might be possible to cook something up with the Obj module, like the internals of printf 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 generalized curry or uncurry 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).

蹲在坟头点根烟 2024-10-15 13:30:28

该语言本身不允许您在任意大小的元组上定义函数。

然而,可以通过遵循这种折叠技术来定义具有任意数量参数的函数(它是针对 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文