4

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

3
  • One thing to consider: What do you want to happen if there is no tuple (i.e. your Maybe value contains a Nothing)? Commented Feb 13, 2016 at 20:31
  • 1
    try maybe undefined fst, or (fst <$>). Commented Feb 13, 2016 at 20:42
  • 1
    Why was this downvoted? Commented Jan 20, 2017 at 19:12

2 Answers 2

8

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 
Sign up to request clarification or add additional context in comments.

Comments

2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.