I need a function that works like this:
foo :: Integer -> Integer -> [Integer]
foo a b = do
let result = []
let Coord x y = boo a b
if x > 0
let result = result ++ [3]
if y > 0
let result = result ++ [5]
if x < a
let result = result ++ [7]
if y < b
let result = result ++ [9]
result
I can not use the guards because the result can have more then one element. But as I see I can not use ‘let’ in the ‘if’ expression:
all_possible_combinations.hs:41:14: parse error on input `let'
How can I check multiple expressions and add new elements in the list?
I search not only imperative solution, but the functional one.
Other people have said why what you tried doesn’t work. Here is a concise way of doing what you want:
So how does this work?
We start with a list of pairs. The second element of each pair is the value we might want to include in the return value from
foo. The first element of each pair tells us whether we actually want to include it.Then we call
filter fst, which throws away all the pairs where the condition is false.Finally, we call
map snd, which throws away the conditions (all the ones that are left are true), and keeps the values we are interested in.