我试图了解如何在 Haskell 中通过各种数据类型的参数来记忆函数。我已经为 Ralf Hinze 的文章“ Memo functions, polytypically! ”中的 Tree 类型实现了制表和应用函数。
我的实现如下。我的测试函数计算深度为 d 的树中子树的数量。如果我记住递归调用,这个函数应该更快吗?不是:在我的系统上计时两个版本给出:
helmholtz:LearningHaskell edechter$ time ./Memo 1 23
Not memoized: # of subtrees for tree of depth 23 is: 25165822
real 0m1.898s
user 0m1.886s
sys 0m0.011s
helmholtz:LearningHaskell edechter$ time ./Memo 0 23
Memoized: # of subtrees for tree of depth 23 is: 25165822
real 0m5.129s
user 0m5.013s
sys 0m0.115s
我的代码很简单:
-- Memo.hs
import System.Environment
data Tree = Leaf | Fork Tree Tree deriving Show
data TTree v = NTree v (TTree (TTree v)) deriving Show
applyTree :: TTree v -> (Tree -> v)
applyTree (NTree tl tf) Leaf = tl
applyTree (NTree tl tf) (Fork l r) = applyTree (applyTree tf l) r
tabulateTree :: (Tree -> v) -> TTree v
tabulateTree f = NTree (f Leaf) (tabulateTree $ \l
-> tabulateTree $ \r -> f (Fork l r))
numSubTrees :: Tree -> Int
numSubTrees Leaf = 1
numSubTrees (Fork l r ) = 2 + numSubTrees l + numSubTrees r
memo = applyTree . tabulateTree
mkTree d | d == 0 = Leaf
| otherwise = Fork (mkTree $ d-1) (mkTree $ d-1)
main = do
args <- getArgs
let version = read $ head args
d = read $ args !! 1
(version_name, out) = if version == 0
then ("Memoized", (memo numSubTrees) (mkTree d))
else ("Not memoized", numSubTrees (mkTree d))
putStrLn $ version_name ++ ": # of subtrees for tree of depth "
++ show d ++ " is: " ++ show out
更新
我明白为什么我的函数不会利用记忆,但我仍然不明白如何构建一个确实利用这一点的函数。基于此处的斐波那契记忆示例,我的尝试如下所示:
memofunc :: Tree -> Int
memofunc = memo f
where f (Fork l r) = memofunc l + memofunc r
f (Leaf) = 1
func :: Tree -> Int
func (Leaf) = 1
func (Fork l r) = func l + func r
但这仍然没有做正确的事情:
helmholtz:LearningHaskell edechter$ time ./Memo 0 23
Memoized: # of subtrees for tree of depth 23 is: 8388608
real 0m10.436s
user 0m9.895s
sys 0m0.532s
helmholtz:LearningHaskell edechter$ time ./Memo 1 23
Not memoized: # of subtrees for tree of depth 23 is: 8388608
real 0m1.666s
user 0m1.654s
sys 0m0.011s