Get all permutations of a list in Haskell

后端 未结 8 1087
一整个雨季
一整个雨季 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:03

    Everything is better with monads:

    perm :: [a] -> [[a]]
    perm []     = return []
    perm (x:xs) = (perm xs) >>= (ins x)
        where
        ins :: a -> [a] -> [[a]]
        ins x []     = [[x]]
        ins x (y:ys) = [x:y:ys] ++ ( map (y:) (ins x ys) )
    

    So: you have a function, that inserts letter in a word, but it produces more then one word, so how to apply it recursively? >>= helps!

    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题