Get all permutations of a list in Haskell

后端 未结 8 1174
一整个雨季
一整个雨季 2020-12-15 17:34

I\'m trying to do this from scratch, without the use of a library outside the standard lib. Heres my code:

permutations :: [a] -> [[a]]
permutations (x:xs         


        
8条回答
  •  被撕碎了的回忆
    2020-12-15 17:55

    For a simple implementation without considering duplications in the input

    permutations :: Eq a => [a] -> [[a]]
    permutations [] = [[]]
    permutations as = do a <- as
                         let l = delete a as
                         ls <- permutations l
                         return $ a : ls
    

    Test:

    λ> permutations [1,2,3]
    [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
    λ> permutations "abc"
    ["abc","acb","bac","bca","cab","cba"]
    λ> 
    

    Algorithm Reference

提交回复
热议问题