这是在Haskell的Data.List
模块permutations
函数的代码:Haskell置换库函数 - 请澄清一下?
permutations :: [a] -> [[a]]
permutations xs0 = xs0 : perms xs0 []
where
perms [] _ = []
perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)
where interleave xs r = let (_,zs) = interleave' id xs r in zs
interleave' _ [] r = (ts, r)
interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r
in (y:us, f (t:y:us) : zs)
有人能花时间向我解释这段代码是如何工作的?
我的困惑源于我非常习惯于编写没有外部依赖(即使它们嵌套在另一个函数中)的函数,尤其是如果它们是递归的。由于permutations
里面perms
以及t
和ts
里面interleave'
,我就失去了功能的流程。
谢谢!
有很多不同的方式来编写'排列'。这个不是最快的。但它有一个有趣的属性,最快的版本并没有。 – Carl
即,它适用于无限列表。 –