在 F# 中重载函数调用行为?
能做到吗?我一直在四处挖掘,但没有发现任何关于这是否可能的信息。
我想要重载函数调用行为的主要原因是我最终得到了一些使用一些非常复杂的闭包的代码,这些闭包捕获了大量要使用的本地状态。
我发现这种嵌套闭包确实令人困惑,并且希望将它们转换为具有明确定义的模式和继承等的成熟对象,而不更改其余代码的接口。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
F# 不支持函数应用行为的重载,因此您无法编写可以像函数一样调用的对象。恐怕您必须更改接口才能使用以下内容:
而不是:
对象的使用通常也表明实体更复杂,因此通过更改接口,您可以向调用它的开发人员提供一些提示(说这是一个复杂类型)。根据您的域,您还应该为
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:
Instead of:
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).