F#代码组织:类型&模组 [英] F# code organization: types & modules

查看:118
本文介绍了F#代码组织:类型&模组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何决定是在模块内部编写函数还是作为某种类型的静态成员进行编写?

How do you decide between writing a function inside a module or as a static member of some type?

例如,在F#的源代码中,有许多类型的定义以及同名模块,如下所示:

For example, in the source code of F#, there are lots of types that are defined along with a equally named module, as follows:

type MyType = // ...

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module MyType = // ...

为什么不简单地将操作定义为MyType类型的静态成员?

Why don't you simply define the operations as static members of type MyType?

推荐答案

以下是有关技术区别的说明.

Here are some notes about the technical distinctions.

可以打开模块(除非它们具有RequireQualifiedAccessAttribute).也就是说,如果将功能(FG)放在模块(M)中,则可以编写

Modules can be 'open'ed (unless they have RequireQualifiedAccessAttribute). That is, if you put functions (F and G) in a module (M), then you can write

open M
... F x ... G x ...

而使用静态方法,您总是会写

whereas with a static method, you'd always write

... M.F x ... M.G x ...

模块函数不能重载.模块中的函数是束缚的,束缚函数不允许重载.如果您想同时呼叫这两个人

Module functions cannot be overloaded. Functions in a module are let-bound, and let-bound functions do not permit overloading. If you want to be able to call both

X.F(someInt)
X.F(someInt, someString)

您必须使用类型的member,该类型仅适用于限定"调用(例如type.StaticMember(...)object.InstanceMember(...)).

you must use members of a type, which only work with 'qualified' calls (e.g. type.StaticMember(...) or object.InstanceMember(...)).

(还有其他区别吗?我不记得了.)

(Are there other differences? I can't recall.)

那些是主要技术差异,它们会影响一个人对另一个人的选择.

Those are the main technical differences that influence the choice of one over the other.

此外,F#运行时(FSharp.Core.dll)中存在一些趋势,即仅将模块用于特定于F#的类型(与其他.Net语言进行互操作时通常不使用)以及用于API的静态方法对语言更加中立.例如,所有带有curried参数的函数都出现在模块中(curved函数对于从其他语言进行调用很重要).

Additionally, there is some tendency in the F# runtime (FSharp.Core.dll) to use modules only for F#-specific types (that are typically not used when doing interop with other .Net languages) and static methods for APIs that are more language-neutral. For example, all the functions with curried parameters appear in modules (curried functions are non-trivial to call from other languages).

这篇关于F#代码组织:类型&amp;模组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆