Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the first Just value from [Maybe a]

Say I have a list like:

[Nothing, Just 1, Nothing, Just 2]

I want to get the first Just (non-error) value; in this case, it's Just 1. The only thing I can think of is:

firstJust xs = case filter isJust xs of
                 []     -> Nothing
                 Just x -> Just x

Is there a better/monad-generic way to do this?

like image 815
kirbyfan64sos Avatar asked Apr 04 '16 19:04

kirbyfan64sos


2 Answers

msum from Control.Monad:

\> msum [Nothing, Just 1, Nothing, Just 2]
Just 1

or asum from Data.Foldable:

\> asum [Nothing, Just 1, Nothing, Just 2]
Just 1

Both are documented as:

The sum of a collection of actions, generalizing concat.

with signature:

msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
asum :: (Foldable t, Alternative f) => t (f a) -> f a

and behave as above due to Maybe instance of Alternative.

like image 136
behzad.nouri Avatar answered Oct 21 '22 01:10

behzad.nouri


import Data.Foldable (find)
import Data.Maybe (isJust)
import Control.Monad (join)

firstJust = join . find isJust

Usage:

> firstJust [Nothing, Just 1, Nothing, Just 2]
Just 1

> firstJust [Nothing, Nothing]
Nothing
like image 36
ZhekaKozlov Avatar answered Oct 21 '22 00:10

ZhekaKozlov