How do you extract the first element from a Maybe
tuple? I have tried to use fst
but that doesn't seem to work.
Since Maybe
is a functor, use fmap
to lift fst :: (a, b) -> a
to work with Maybe (a,b)
.
> :t fmap fst
fmap fst :: Functor f => f (b, b1) -> f b
> fmap fst $ Just (3, 6)
Just 3
> fmap fst $ Nothing
Nothing
Of course, this returns a Maybe a
, not an a
, so you can use the maybe
function to unpack the result (and provide a default value if the Maybe (a, b)
is actually Nothing
):
> import Data.Maybe
> maybe 0 fst (Just (3, 6))
3
> maybe 0 fst Nothing
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With