gpt4 book ai didi

F# 等效于具有案例类/可区分联合的 Scala lazy val

转载 作者:行者123 更新时间:2023-12-02 01:41:17 31 4
gpt4 key购买 nike

在 Scala 中我可以这样做:

abstract class MyData
case class A() extends MyData
case class B() extends MyData

implicit class HeavyComputationProvider(val data : MyData) {
private def _HeavyComputation() = /* */;
lazy val HeavyComputation = this._HeavyComputation();
}

// Example usage:
val a = A
println a.HeavyComputation // This will calculate
println a.HeavyComputation // This will use the cached value

这样的好处是在重新使用时缓存,但在不使用时不计算。

如何为以下 F# 类型提供惰性 HeavyComputation

type MyData =
| A
| B

type MyData with
member private this.__HeavyComputation = (* *)

// Error: This declaration element is not permitted in an augmentation and this is unavailable
let _HeavyComputation = lazy((* *))
// This will just create a *new* lazy computation each time
member this._HeavyComputation = lazy(this.__HeavyComputation)
// This should lazily compute & cache, transparent to the caller
member this.HeavyComputation = this._HeavyComputation.Force

最佳答案

我认为没有直接等同于 Scala 方法的方法。这样做需要保留一些额外的状态作为对象的一部分(例如惰性值),并且 F# 不允许您在对象定义后向它们添加额外的状态。

您可以做的最接近的事情是编写一个包装器类型,将原始 MyData 值与额外的惰性计算一起存储:

type MyData =
| A
| B

type MyDataWithComputation(data:MyData) =
let _HeavyComputation = lazy(1)
member this.MyData = data
member this.HeavyComputation = _HeavyComputation.Value

然后按如下方式使用它:

let myd = MyDataWithComputation(A)
myd.HeavyComputation
myd.HeavyComputation

关于F# 等效于具有案例类/可区分联合的 Scala lazy val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28479272/

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