Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: How to get element from a Maybe tuple

Tags:

haskell

How do you extract the first element from a Maybe tuple? I have tried to use fst but that doesn't seem to work.

like image 914
karambit Avatar asked Oct 11 '25 19:10

karambit


1 Answers

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
like image 166
chepner Avatar answered Oct 14 '25 12:10

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!