karambit
karambit

Reputation: 167

Haskell: How to get element from a Maybe tuple

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

Upvotes: 4

Views: 3597

Answers (2)

chepner
chepner

Reputation: 531055

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

Upvotes: 8

arrowd
arrowd

Reputation: 34401

You can pattern match on Maybe value using case, for example:

case mbVal of
  Just x -> fst x
  Nothing -> ...

You can also use fromJust if you are sure the value is Just.

Finally, you can match the first element of a tuple right away:

case mbVal of
  Just (x,_) -> x

Upvotes: 2

Related Questions