Get all permutations of a list in Haskell

后端 未结 8 1143
一整个雨季
一整个雨季 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 18:07

    I think that this is shorter and more elegant variant for what others are suggesting:

    permutate :: (Eq a) => [a] -> [[a]]
    permutate [] = [[]]
    permutate l = [a:x | a <- l, x <- (permutate $ filter (\x -> x /= a) l)]
    

提交回复
热议问题