在 F# 中重载函数调用行为?

发布于 2024-12-15 10:15:49 字数 172 浏览 1 评论 0原文

能做到吗?我一直在四处挖掘,但没有发现任何关于这是否可能的信息。

我想要重载函数调用行为的主要原因是我最终得到了一些使用一些非常复杂的闭包的代码,这些闭包捕获了大量要使用的本地状态。

我发现这种嵌套闭包确实令人困惑,并且希望将它们转换为具有明确定义的模式和继承等的成熟对象,而不更改其余代码的接口。

Can it be done? I've been digging around and haven't found anything as to whether or not it is possible.

The main reason I want to overload function call behavior is I have ended up with some code which uses some really complex closures, which capture lots and lots of local state to work with.

I find this sort of nested closures really confusing, and would like to convert them to full-fledged objects with a well-defined schema and inheritance and such, without changing the interface to the rest of the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

想你只要分分秒秒 2024-12-22 10:15:54

F# 不支持函数应用行为的重载,因此您无法编写可以像函数一样调用的对象。恐怕您必须更改接口才能使用以下内容:

foo.Invoke(10, "Hello")

而不是:

foo 10 "Hello"

对象的使用通常也表明实体更复杂,因此通过更改接口,您可以向调用它的开发人员提供一些提示(说这是一个复杂类型)。根据您的域,您还应该为 Invoke 找到一些更具描述性的名称。

我还更改了语法以使用元组方法参数而不是柯里化样式 - 从技术上讲,您也可以对成员使用柯里化样式,但它并不普遍使用(它对于简单函数来说效果更好)。

最后,如果您发现闭包表示更复杂的数据结构,也许您可​​以使数据结构更明确并定义一个 type 来保存数据。然后,您可以只使用普通函数,但将数据作为附加参数提供给它们(尽管这只是一个想法,可能对您来说并不真正有用)。

F# does not support overloading of function application behavior, so you can't write object that can be invoked in the same way as function. I'm afraid that you'll have to change the interface to use something like:

foo.Invoke(10, "Hello")

Instead of:

foo 10 "Hello"

The use of objects generally also suggests that the entity is more complex, so by changing the interface, you give some hint to the developer calling it (saying that this is a complex type). Depending on your domain, you should also find some more descriptive name for Invoke.

I also changed the syntax to use tupled method parameters instead of curried style - technically, you can use curried style for members too, but it is not generally used (it just works better for simple functions).

Finally, if you're finding that the closures represent more complex data structure, maybe you could make the data structure more explicit and define a type to hold the data. Then you could just use plain functions, but give them the data as an additional argument (although this is just a thought that may not really be useful for you).

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