F# 相当于 Scala lazy val with case class/discriminated union

F# equivalent to Scala lazy val with case class/discriminated union

在 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