5

I have a list comprehension in Haskell that specifies a predicate on a Maybe type:

[x | x <- listOfMaybes, isJust(f y), x == fromJust(f y)]

is there a way to simplify this expression?

3
  • 1
    Please provide a fully working example. Without <-, this is not a list comprehension and I doubt it compiles. Commented Mar 20, 2015 at 12:14
  • updated the code snippet Commented Mar 20, 2015 at 12:17
  • 1
    I think the x==fromJust(f y) in the list comprehension isn't necessary. Conditioning on isJust(f y) does the job. Commented Mar 20, 2015 at 12:28

2 Answers 2

20

If you simply want to filter out all the Nothings, shang's answer gives the most concise solution. However, it can be done easily in a list comprehension:

[x | Just x <- f y] 
Sign up to request clarification or add additional context in comments.

4 Comments

You might want to explain that this is essentially flip concatMap (f y) $ \result -> case result of {Just x -> [x]; {-Implicitly added!-} _ -> []}
Right, I find it easier to just learn that pattern matching in list comprehensions is perfectly valid and automatically filters out non-matching cases. Your desugaring is not exactly adding clarity, I find :-)
interesting that the behaviour is different here from pattern matching in do notation where Just x <- f y might error
It wouldn't be different to do notation, because it's the monad instance of List that controls how pattern matching errors are handled. And in List, error simply is ignored. This might have changed recently due to the MonadFail proposal, I'm not sure.
16

You can simply use catMaybes (from Data.Maybe) to filter out all Nothing values.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.