gpt4 book ai didi

F#代码组织: types & modules

转载 作者:行者123 更新时间:2023-12-03 13:26:01 25 4
gpt4 key购买 nike

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

例如,在 F# 的源代码中,有很多类型与同名模块一起定义,如下所示:

type MyType = // ...

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

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

最佳答案

除了其他答案之外,还有另一种使用模块的情况:

对于值类型,它们可以帮助定义不会在每次访问时重新评估的静态属性。例如:

type [<Struct>] Point =
val x:float
val y:float
new (x,y) = {x=x;y=y}

static member specialPoint1 = // sqrt is computed every time the property is accessed
Point (sqrt 0.5 , sqrt 0.5 )

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

let specialPoint2 = // sqrt is computed only once when the Module is opened
Point (sqrt 0.5 , sqrt 0.5 )

关于F#代码组织: types & modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com