下面的输出是15,9,9,但是我想要15,9,21我想保留一个懒惰的版本,这样我就可以在组合函数中放入一个新的函数版本。
open System
let mutable add2  = fun x-> x+2
let mutable mult3 = fun x-> x*3
let mutable co = add2 >> mult3
let mutable com = lazy( add2 >> mult3)
let mutable com2 = com
add2<- fun x-> x
co 3|> printfn "%A"
com.Force() 3|> printfn "%A"
add2<- fun x-> x+4
com2.Force() 3|> printfn "%A"发布于 2019-04-02 05:09:12
我不认为这里需要惰性值--惰性值在需要时只计算一次,但它的值在需要后不会改变。在您的示例中,您需要Force重新计算该值,以防某些依赖项发生更改。您可以定义如下内容:
type Delayed<'T> = 
  | Delayed of (unit -> 'T)
  member x.Force() = let (Delayed f) = x in f()
let delay f = Delayed f它使用Force方法表示一个延迟值(实际上,只是一个函数),该方法将在每次访问它时对其求值。如果你使用delay重写你的代码,它会按照你想要的那样运行:
let mutable add2 = fun x-> x+2
let mutable mult3 = fun x-> x*3
let mutable com = delay(fun () -> add2 >> mult3)
let mutable com2 = com
add2 <- fun x -> x
com.Force() 3 |> printfn "%A"
add2 <- fun x -> x + 4
com2.Force() 3 |> printfn "%A"与lazy不同的是,它不做任何缓存,所以调用两次Force只会做两次。您可以通过跟踪计算的依赖关系图来添加一些缓存,但这会变得更加复杂。
https://stackoverflow.com/questions/55452066
复制相似问题