Haskell递归:Haskell编程中的交错函数

时间:2015-07-07 14:52:48

标签: haskell recursion

我无法弄清楚Haskell Ch.11中的编程中以下'interleave'函数的递归机制如何工作。

-- Definition
interleave :: a -> [a] -> [[a]]
interleave a [] = [[a]]
interleave x (y:ys) = (x:y:ys):map (y:) (interleave x ys)

-- Example
> interleave 3 [4,5,6,7]
[[3,4,5,6,7],[4,3,5,6,7],[4,5,3,6,7],[4,5,6,3,7],[4,5,6,7,3]]

它是如何在引擎盖下工作的?

我坚持这样的推理:

interleave 3 [4,5,6,7]
= [3,4,5,6,7]:map (4:) (interleave 3 [5,6,7])
= [3,4,5,6,7]:[4,3,5,6,7]:map (5:) (interleave 3 [6,7])
= [3,4,5,6,7]:[4,3,5,6,7]:[5,3,6,7]:map (6:) (interleave 3 [7])
= [3,4,5,6,7]:[4,3,5,6,7]:[5,3,6,7]:[6,3,7]:map (7:) (interleave 3 [])
= [3,4,5,6,7]:[4,3,5,6,7]:[5,3,6,7]:[6,3,7]:[7,3]:[[3]]

= [[3,4,5,6,7],[4,3,5,6,7],[5,3,6,7],[6,3,7],[7,3],[3]]
???
/= [[3,4,5,6,7],[4,3,5,6,7],[4,5,3,6,7],[4,5,6,3,7],[4,5,6,7,3]]

请赐教。非常感谢。

1 个答案:

答案 0 :(得分:3)

在第二和第三行之间你错过了一些东西:

[3,4,5,6,7]:map (4:) (interleave 3 [5,6,7])
= [3,4,5,6,7]:map (4:) ([3,5,6,7]:map (5:) (interleave 3 [6,7]))
= [3,4,5,6,7]:[4,3,5,6,7]:map (4:) (map (5:) (interleave 3 [6,7]))

所以最后你有一堆map (x:),所有列表都包含原始列表的所有元素