我试图在Haskell中实现一个列表的排列。排列的想法是这样的:Haskell中的排列实现
基本情况是当列表长度为0和1时,它是列表本身,当大小为2时,排列给出列表本身以及交换元素。
现在,给出一个列表[a,b,c,d]我们排列[b,c,d]并附加一个。并且我们改变我们的列表,使其在第一个b中像[b,a,c,d]和递归地排列[a,c,d]等等。
到目前为止,我在Haskell中完成了以下代码。这完美的作品。但我对这包含的'haskell-ness'的级别不满意。我想提供一些关于如何在Haskell中更加可读和高效的提示。提前致谢。代码如下:
-- swap the first element of a list with the element at the index
swapFirstWith index l | index == 0 = l
| otherwise = [l!!index]
++ (take (index-1) (tail l))
++ [head l]
++ (drop (index+1) l)
permutations :: [a] -> [[a]]
permutations [] = [[]]
permutations [a] = [[a]]
permutations [a,b] = [[a,b], [b,a]]
permutations lst = foldl (++) [] (map (\x-> miniperms x) swappedList)
where miniperms l = map (\x-> (head l): x) $ permutations (tail l)
swappedList = map (\(i, x) -> swapFirstWith i lst) (zip [0..] lst)
main = do
putStrLn $ show $ perms
putStrLn $ show $ length perms
where lst = [1,2,3,4,5,6,7,8,9]
perms = permutations lst
你可以看一下[base in implementation](http://hackage.haskell.org/package/base-4.10.0.0/docs/src/Data.OldList.html#permutations),它有很好的讨论[这个问题和答案](https://stackoverflow.com/questions/24484348)。 – Cirdec