Tshimanga
Tshimanga

Reputation: 885

then and else parse error in Haskell List Comprehension

So there was an example in Learn You A Haskell that I wanted to recast using list comprehension. Basically it should be a simple function f:[a]->[Char] as follows

let sayMe xs = [ if x <- [1..5] then show x else "Not a desired value" | x <- xs]

Unfortunately when I try to define the function I get the following error:

parse error in if statement: missing required then and else clauses

However, I do have the then and else clauses there and my function isn't, as far as I can tell, very far off from another example in the book which I have verified as working:

let sayMe xs = [if x<10 then "Bang!" else "Boom!"|x<-xs, odd x]

I know that there are other ways to do this, but I'd like to understand why this particular method isn't working the way I think it should.

Upvotes: 1

Views: 583

Answers (1)

dfeuer
dfeuer

Reputation: 48611

An if-then-else expression has three parts: a condition, a True branch, and a False branch. Each of these parts must be an expression. x <- [1..5] is not an expression; it's part of list comprehension syntax. You could express that concept with an expression, however.

[ if 1 <= x && x <= 5 then show x else "Not a desired value" | x <- xs ]

If the things you're interested in are not consecutive, you can use the elem function:

[ if x `elem` [1,17,94,12] then show x else "Not a desired value" | x <- xs ]

Upvotes: 4

Related Questions