pri*_*tor 5 recursion f# caching memoization y-combinator
我有一个coins = [200; 100; 50; 20; 10; 5; 2; 1] 列表和这个递归函数来计算有多少种方法可以提供一定量的变化(Project Euler 问题 31 的剧透警报):
let rec f acc coins amount =
if amount < 0 then 0L
elif amount = 0 then acc
else
match coins with
| [] -> 0L
| c::cs ->
f (acc + 1L) coins (amount - c) + f acc cs amount
Run Code Online (Sandbox Code Playgroud)
除了 aStackOverflowException对于大值之外,该函数需要很长时间。所以我想起了Y 组合器,并很好奇如何将它应用于这个问题。在一点帮助和对函数签名的两个小改动后,我得到了这个:
let f f acc coins amount =
if amount < 0 then 0L
elif amount = 0 then acc
else
match coins with
| [] -> 0L
| c::cs ->
f (acc + 1L) coins (amount - c) + f acc cs amount
let rec Y f x = f (Y f) x
Run Code Online (Sandbox Code Playgroud)
这有效,现在我想使用字典进行缓存。但为此,我不知道如何处理acc和 的coins参数f。
在下面的代码中,字典已经有一个疯狂的类型。在对函数进行柯里化之后,它变成了int -> int64,所以我希望我的字典有这两个类型参数,但它没有。它编译并给出正确的答案,但对于大输入它仍然很慢——对于这种类型,这并不奇怪。
open System.Collections.Generic
let memoize (d:Dictionary<_, _>) f x =
match d.TryGetValue(x) with
| true, re -> re
| _ ->
let re = f x
d.Add(x, re)
re
let numberOfWaysToChange =
let d = Dictionary<_,_>()
fun x -> Y (f >> fun f x -> memoize d f x) 0L coins x
Run Code Online (Sandbox Code Playgroud)
我尝试0L在所有地方粘贴两个初始化参数和列表,但我无法让任何其他变体工作。
我怎样才能使这个例子中的缓存工作,我。e. 我必须如何修复参数才能使我的缓存类型为Dictionary<int, int64>?
PS:我知道 myf不是尾递归的,所以我可以省去accumulator 参数的麻烦(还需要学习延续)。
您已经差不多完成了,您只需要将 Y 组合器的功能集成到递归记忆函数中即可。
let rec Y f x = f (Y f) x
// val Y : f:(('a -> 'b) -> 'a -> 'b) -> x:'a -> 'b
let memoize f =
let d = new System.Collections.Generic.Dictionary<_,_>()
let rec g x =
match d.TryGetValue x with
| true, res -> res
| _ -> let res = f g x in d.Add(x, res); res
g
// val memoize : f:(('a -> 'b) -> 'a -> 'b) -> ('a -> 'b) when 'a : equality
Run Code Online (Sandbox Code Playgroud)
调整算法。
let cc f = function
| amount, _ when amount = 0 -> 1
| amount, _ when amount < 0 -> 0
| _, [] -> 0
| amount, hd::tl -> f (amount, tl) + f (amount - hd, hd::tl)
#time;;
Y cc (200, [200; 100; 50; 20; 10; 5; 2; 1])
memoize cc (200, [200; 100; 50; 20; 10; 5; 2; 1])
Run Code Online (Sandbox Code Playgroud)