【发布时间】:2013-12-31 04:20:14
【问题描述】:
This memoize function 在运行时在 () -> 'a 类型的任何函数上失败,并出现 Null-Argument-Exception。
let memoize f =
let cache = System.Collections.Generic.Dictionary()
fun x ->
if cache.ContainsKey(x) then
cache.[x]
else
let res = f x
cache.[x] <- res
res
有没有办法编写一个也适用于() -> 'a 的 memoize 函数?
(我目前唯一的选择是使用Lazy 类型。调用x.Force() 来获取值。)
【问题讨论】:
-
Memoize 通常用于在参数用作查找键的情况下缓存一些计算。在这种情况下,
Lazy是正确的工具。 -
你可以包装
lazy,像这样:let memoize f = let result = lazy (f()) in fun () -> result.Value