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

查看:28
本文介绍了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 ...

模块函数不能重载.模块中的函数是 let-bound,并且 let-bound 函数不允许重载.如果您想同时调用两者

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)

你必须使用一个类型的 members,它只适用于限定"调用(例如 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 的静态方法更加中性.例如,所有带有柯里化参数的函数都出现在模块中(柯里化函数从其他语言调用是很重要的).

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天全站免登陆