记住`地图'来电

时间:2014-11-15 21:36:27

标签: haskell dynamic-programming

我理解这个便笺的工作原理

fib :: Int -> Int
fib = (map fib' [0..] !!)                 
     where fib' 1 = 1                                                        
           fib' 2 = 1                                                        
           fib' n = fib (n-2) + fib (n-1) 

但是如何记忆使用上述功能的这个功能。

fibsFor :: [Int] -> [Int]
fibsFor xs = map fib xs

如何让每次调用fib使用相同的缓存?

1 个答案:

答案 0 :(得分:2)

使用相同的“缓存”。注意fib永远不会为同一个参数计算两次。

import Debug.Trace

fib :: Int -> Int
fib = (map (fib' . (\i -> trace ("fib called on " ++ show i) i)) [0..] !!)
     where fib' 1 = 1
           fib' 2 = 1
           fib' n = fib (n-2) + fib (n-1)

fibsFor :: [Int] -> [Int]
fibsFor xs = map fib xs


*Main> fibsFor [5, 10, 20]
[fib called on 5
fib called on 3
fib called on 1
fib called on 2
fib called on 4
5,fib called on 10
fib called on 8
fib called on 6
fib called on 7
fib called on 9
55,fib called on 20
fib called on 18
fib called on 16
fib called on 14
fib called on 12
fib called on 11
fib called on 13
fib called on 15
fib called on 17
fib called on 19
6765]