What i want to do is create a function that given a certain length creates all possible combinations/permutations of True/False
ex. getPerm 2 shall 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 get it right..im new to functional programming so please only use basic stuff and not weird things..try to make code as simple as possible cuz i don't know a lot about haskell yet
getPerm n = concat $ replicateM n [True, False]
While it might qualify as a "weird thing", it isn't too hard. [True, False] represents nondeterministic choice in the list monad. replicateM makes a nondeterministic list of n repetitions of these choices. Since you wanted them all in one list we concatenate to get the final result.
You get your result by using sequence:
getPerm = concat . sequence . flip replicate [True,False]
If you want to have different lists for all permutations, just drop the concat.
I just thought of a more basic definition. iterate :: (a -> a) -> a -> [a] applies a function again and again and returns the intermediate values:
getPerm = concat . (iterate permute [[]] !!)
permute xs = map (True:) xs ++ map (False:) xs
So basically, permute generates the next permutation, while getPerm just picks the permutation needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With