1

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.

1 Answer 1

4

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 ]
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I see. Odd that the expression x<-set isn't considered an "expression". Thanks for the help!
@Tshimanga, it's not actually odd. Drawing from a list is quite different from checking if a value is in a list. If the syntax worked for both, it would sometimes be ambiguous. This is not the Haskell way. Also, you'll soon learn other ways <- is used that have nothing to do with lists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.