Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a list of values from a list of maybes without fromJust

Tags:

haskell

Input: [Just "foo", Just "bar", Nothing, Just "quux"]

Output: ["foo", "bar", "quux"]

I'm not satisfied with the following solution using fromJust because it's not very portable to elm which doesn't like unsafe functions:

extract list = map fromJust $ filter isJust list

Is there another concise / idiomatic way to achieve this?

like image 826
Delapouite Avatar asked Jul 28 '16 16:07

Delapouite


2 Answers

You can use catMaybes:

import Data.Maybe
catMaybes list
like image 101
Lee Avatar answered Nov 08 '22 17:11

Lee


Λ: :m + Data.Maybe
Λ: concatMap maybeToList [Just "foo", Just "bar", Nothing, Just "quux"]
["foo","bar","quux"]
like image 43
pdexter Avatar answered Nov 08 '22 18:11

pdexter