F#记录成员评估 [英] F# record member evaluation

查看:82
本文介绍了F#记录成员评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么每次通话都会评估t.b?并且有什么方法可以使它只评估一次?

Why is t.b evaluated on every call? And is there any way how to make it evaluate only once?

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

let t = { a = 1. }
t.b
t.b

推荐答案

这是一个属性;您基本上是在呼叫get_b()成员.

It's a property; you're basically calling the get_b() member.

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

If you want the effect to happen once with the constructor, you could use a class:

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

这篇关于F#记录成员评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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