這是在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
即,它適用於無限列表。 –