The program return all possible combinations of '0' and '1' length N.
addToElement :: String -> String -> String
addToElement element symbol = element ++ symbol
addOneToElement :: String -> String
addOneToElement element = addToElement element "1"
addZeroToElement :: String -> String
addZeroToElement element = addToElement element "0"
processListOnce :: [String] -> [String]
processListOnce lst = do
let s1 = map addOneToElement lst
let s2 = map addZeroToElement lst
s1 ++ s2
processList :: [String] -> Integer -> [String]
processList lst 1 = processListOnce lst
processList lst n = do
let tmp = processListOnce(lst)
processList tmp (n - 1)
{-
processList2 :: [String] -> Integer -> [String]
processList2 lst n = iterate (map processListOnce) lst !! n
-}
main = do
let s = processList ["0", "1"] 2
let ss = show s
putStrLn ss
It is my first Haskell program so I will be thankful if you help me:
First of all pls refactore my code Haskell-way. I already know one magic refactring:
Control.Monad.replicateM n [0,1]
but this solution is not good for studying purposes :)
Why I can not use ProcessList2 instead ProcessList and get error:
all_possible_combinations.hs:44:51: Couldn't match expected type `[Char]' against inferred type `Char' Expected type: [String]] Inferred type: [String] In the second argument of `iterate', namely `lst' In the first argument of `(!!)', namely `iterate (map processListOnce) lst'
Is there any way to skip (not use) the 'tmp' variable in the processList? I have tried, but got the error:
processList :: [String] -> Integer -> [String] processList lst 1 = processListOnce lst processList lst n = processList processListOnce(lst) (n - 1) all_possible_combinations.hs:39:32: Couldn't match expected type `[String]' against inferred type `[String] -> [String]' In the first argument of `processList', namely `processListOnce' In the expression: processList processListOnce (lst) (n — 1) In the definition of `processList': processList lst n = processList processListOnce (lst) (n — 1)
Thanks in advance.