F#记录会员评价
为什么每次调用都要评估 tb ?有什么办法让它只评估一次吗?
type test =
{ a: float }
member x.b =
printfn "oh no"
x.a * 2.
let t = { a = 1. }
t.b
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Brian 答案的替代版本最多评估一次
b
,但如果从未使用过B
则根本不会评估它An alternative version of Brian's answer that will evaluate
b
at most once, but won't evaluate it at all ifB
is never used它是一种财产;您基本上是在调用
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:
为了回应您在 Brian 帖子中的评论,您可以使用可选/命名参数来伪造复制和更新记录表达式。例如:
In response to your comments in Brian's post, you can fake copy-and-update record expressions using optional/named args. For example:
之前的回复建议切换到类,而不是使用记录。如果您想保留记录(因为其简单的语法和不变性),您可以采用这种方法:
如果
test
的实例是由另一个库(例如来自 Web 的数据提供者)创建的,这非常有用服务或数据库)。使用这种方法时,您必须记住先通过初始化函数传递从该 API 接收到的任何test
实例,然后再在代码中使用它。The previous responses suggest switching to a class, instead of using a record. If you want to stay with records (for their simple syntax and immutability), you can take this approach:
This is useful if the instance of
test
is created by another library (like a data provider from a web service or database). With this approach, you must remember to pass any instance oftest
that you receive from that API through the initialize function before using it in your code.