Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter over [Maybe a] and discard Nothing values

With a list of Maybe a, how to filter and take only the elements of the list which are not Nothing?

-- input
pas = [Just 3, Just 1, Just 5, Just 9, Nothing, Just 10, Nothing] :: [Maybe Int]

-- expected output
new_pas = [3, 1, 5, 9, 10]

I've tried different ways of using map and looked at mapMaybe but can't find the right combination.

like image 536
Jivan Avatar asked Dec 30 '22 20:12

Jivan


2 Answers

As well as the simple list comprehension you found, there is already a library function for this: catMaybes

And note that you can search Hoogle not only for names, but for type signatures - something which is really useful in many situations. Here entering [Maybe a] -> [a] gives you catMaybes straight away. (Confession: I'd forgotten the name of the function, but knowing it existed, found it exactly that way just now!)

like image 106
Robin Zigmond Avatar answered Jan 06 '23 22:01

Robin Zigmond


While typing the question I've found the answer and it's actually straightforward:

new_pas = [pa | Just pa <- pas]
-- [3, 1, 5, 9, 10]

Putting it here for other people Googling the same question.

like image 24
Jivan Avatar answered Jan 06 '23 21:01

Jivan