F#记录会员评估

Old*_*vec 12 f# record member

为什么每次通话都要评估tb?有没有什么方法可以让它只评估一次?

type test =
  { a: float }
  member x.b =
    printfn "oh no"
    x.a * 2.

let t = { a = 1. }
t.b
t.b
Run Code Online (Sandbox Code Playgroud)

GS *_*ica 15

Brian的答案的替代版本,b最多只评估一次,但如果B从未使用过,则根本不评估它

type Test(a:float) =
    // constructor
    let b = lazy
                 printfn "oh no"
                 a * 2.
    // properties
    member this.A = a
    member this.B = b.Value
Run Code Online (Sandbox Code Playgroud)


Bri*_*ian 13

这是一个属性; 你基本上是在打电话给get_b()会员.

如果希望效果在构造函数中发生一次,则可以使用类:

type Test(a:float) =
    // constructor
    let b =   // compute it once, store it in a field in the class
        printfn "oh no"
        a * 2.
    // properties
    member this.A = a
    member this.B = b
Run Code Online (Sandbox Code Playgroud)

  • 是的,但您可以编写带有可选参数的构造函数,并获得非常相似的效果. (2认同)