【发布时间】:2011-07-29 23:23:36
【问题描述】:
我正在尝试找到一种正式的方式来考虑 haskell 中的空间复杂性。我发现this article 是关于 Graph Reduction (GR) 技术的,这在我看来是一种可行的方法。但我在某些情况下应用它时遇到问题。考虑以下示例:
假设我们有一棵二叉树:
data Tree = Node [Tree] | Leaf [Int]
makeTree :: Int -> Tree
makeTree 0 = Leaf [0..99]
makeTree n = Node [ makeTree (n - 1)
, makeTree (n - 1) ]
还有两个遍历树的函数,一个 (count1) 可以很好地流式传输,另一个 (count2) 可以一次在内存中创建整个树;根据分析器。
count1 :: Tree -> Int
count1 (Node xs) = 1 + sum (map count1 xs)
count1 (Leaf xs) = length xs
-- The r parameter should point to the root node to act as a retainer.
count2 :: Tree -> Tree -> Int
count2 r (Node xs) = 1 + sum (map (count2 r) xs)
count2 r (Leaf xs) = length xs
我想我理解它在 count1 的情况下是如何工作的,以下是我认为在图形缩减方面发生的情况:
count1 $ makeTree 2
=> 1 + sum $ map count1 xs
=> 1 + sum $ count1 x1 : map count1 xs
=> 1 + count1 x1 + (sum $ map count1 xs)
=> 1 + (1 + sum $ map count1 x1) + (sum $ map count1 xs)
=> 1 + (1 + sum $ (count1 x11) : map count1 x1) + (sum $ map count1 xs)
=> 1 + (1 + count1 x11 + sum $ map count1 x1) + (sum $ map count1 xs)
=> 1 + (1 + count1 x11 + sum $ map count1 x1) + (sum $ map count1 xs)
=> 1 + (1 + 100 + sum $ map count1 x1) + (sum $ map count1 xs)
=> 1 + (1 + 100 + count x12) + (sum $ map count1 xs)
=> 1 + (1 + 100 + 100) + (sum $ map count1 xs)
=> 202 + (sum $ map count1 xs)
=> ...
我认为从序列中可以清楚地看出它在恒定空间中运行,但是在 count2 的情况下会发生什么变化?
我了解其他语言的智能指针,所以我隐约明白 count2 函数中的额外 r 参数不知何故 可以防止树的节点被破坏了,但我想知道确切的机制,或者至少是一种我可以在其他情况下使用的正式机制。
感谢收看。
【问题讨论】:
-
你能说明你如何调用count2吗?您的评论表明您做了类似的事情: let t = makeTree 2 in count2 t t
-
@lngo,是的,here 是我用于测试的代码。
-
你应该阅读一些关于垃圾收集的内容。
-
count2 不在(几乎)恒定空间中运行的事实不是 Haskell 的属性,而是特定 Haskell 实现的属性。即使对 count2 进行垃圾收集也是完全合理的,但它需要编译器证明 count2 的第一个参数永远无法访问。这有点棘手。
-
@Peter -- 线束代码中的 let 绑定不应该对 GC 产生影响。问题不在于名称是否在范围内,而在于对象是否可访问。 SPJ 的两本书中的更多细节:research.microsoft.com/en-us/um/people/simonpj/papers/…
标签: haskell complexity-theory space graph-reduction