So, I recently started learning Haskell and I came across a question where I need to calculate all possible outcomes(2^n) if n number of coins are flipped. For example, if 2 coins are flipped, the output should be [[H, H], [H, T], [T, H], [T, T]]. Similarly, for 3 coins it should be [[H, H, H], [H, H, T], [H, T, H], [T, H, H], [H, T, T], [T, T, H], [T, H, T], [T, T, T]]. My function does not work for arbitrary values of n. It only works if I know n from before. I'm thinking of using recursion but I'm not sure about the syntax.
This is my code:
outcomes(x:xs) = [[a, b] | a <- states x, b <- states (head xs)]
Where, the function states is:
states _ = [True, False]
This function works for n = 2. Please let me know how to make it work for any input n.
You can make use of recursion here. We can construct a function that takes a list of elements [a]
and an Int
, so:
outcomes :: [a] -> Int -> [[a]]
in case the integer is less than or equal to zero, then there is only one possible outcome an empty list. So we return a list that contains one empty list:
outcomes _ n | n <= 0 = [[]]
as for the recursive case, we can take an element from the list, and then recurse with the same list of values, but we create outcomes with one element less, then we prepend the element we took to these outcomes.
outcomes ls n = [ … | x < ls, xs <- … ]
here I leave the …
parts as an exercise. In the first …
fragment, you need to prepend xs
with x
. In the second one, you need to make the recursive call.
So putting this together, we implement outcomes
as:
outcomes :: [a] -> Int -> [[a]]
outcomes _ n | n <= 0 = [[]]
outcomes ls n = [ … | x < ls, xs <- … ]