List all possible 4 chooses from 9 in Haskell

前端 未结 4 1998
温柔的废话
温柔的废话 2021-01-14 10:59

I\'m not able to find an effective way to pick out all permutations of 4 elements from a list of 9 elements in Haskell. The python-way to do the same thing:

         


        
相关标签:
4条回答
  • 2021-01-14 11:20

    Here is my solution:

    import Control.Arrow
    
    select :: [a] -> [(a, [a])]
    select [] = []
    select (x:xs) = (x, xs) : map (second (x:)) (select xs)
    
    perms :: Int -> [a] -> [[a]]
    perms 0 _  = [[]]
    perms n xs = do
        (y, ys) <- select xs
        fmap (y:) (perms (n - 1) ys)
    

    It's very lazy and even works for infinite lists, although the output there is not very useful. I didn't bother implementing diagonalization or something like that. For finite lists it's fine.

    0 讨论(0)
  • 2021-01-14 11:26
    replicateM 4 [1..9]
    

    Will do this for you, I believe. It's in Control.Monad.

    0 讨论(0)
  • 2021-01-14 11:31

    How about this

    import Data.List (delete)
    
    perms :: (Eq a) => Int -> [a] -> [[a]]
    perms 0 _  = [[]]
    perms _ [] = [[]]
    perms n xs = [ (x:ys) | x <- xs, ys <- perms (n-1) (delete x xs) ]
    

    Basically, it says, a permutation of n elements from a set is, pick any element as the first element of the result, then the rest is a permutation of n-1 elements from the rest of the set. Plus some base cases. Assumes that elements in the list are unique.

    0 讨论(0)
  • 2021-01-14 11:33
    pick :: Int -> [a] -> [[a]]
    pick 0 _ = [[]]
    pick _ [] = []
    pick n (x : xs) = map (x :) (pick (n - 1) xs) ++ pick n xs
    
    perms :: Int -> [a] -> [[a]]
    perms n l = pick n l >>= permutations
    
    0 讨论(0)
提交回复
热议问题