How to create a haskell permutation

What I want to do is create a function that sets a specific length, creates all possible combinations / permutations True / False

ex. getPerm 2must return[True,True,True,False,False,True,False,False]

getTrue 0 = []
getTrue size = (True:(getTrue (size-1)))++(True:(getFalse (size-1)))
getFalse 0 = []
getFalse size =(False:(getTrue (size-1)))++(False:(getFalse (size-1)))
getPerm 0 = []
getPerm size= (getTrue size)++(getFalse size)

I can’t understand what is right. New to functional programming, please use only basic things, not weird things. Try to make the code as simple as possible because I don’t know much about haskell yet

+3
source share
3 answers
getPerm n = concat $ replicateM n [True, False]

" ", . [True, False] . replicateM n . , , , .

+5

, sequence:

getPerm = concat . sequence . flip replicate [True,False]

, concat.

. iterate :: (a -> a) -> a -> [a] :

getPerm = concat . (iterate permute [[]] !!)

permute xs = map (True:) xs ++ map (False:) xs

, permute , getPerm .

+3

.

getPerm n 2 ^ n . 0 2 ^ n-1 True False.

getPerms, , .

import Data.Bits

getPerms :: Int -> [[Bool]]
getPerms n = map (encode n) [0..2^n-1]

encode :: Int -> Int -> [Bool]
encode bitSize value = map (testBit value) [0..bitSize-1]

*Main> getPerms 2
[[False,False],[True,False],[False,True],[True,True]]
+2
source

All Articles