Alex Rivera | Logout

Using Maybe type in Haskell

Asked 2010-09-04T16:52:47.243
46

I'm trying to utilize the Maybe type in Haskell. I have a lookup for key, value tuples that returns a Maybe. How do I access the data that was wrapped by Maybe? For example I want to add the integer contained by Maybe with another integer.

Edit
Report

2 Answers

9

Just as a side note: Since Maybe is a Monad, you can build computations using do-notation ...

sumOfThree :: Maybe Int
sumOfThree = do
  a <- someMaybeNumber
  b <- someMaybeNumber
  c <- someMaybeNumber
  let k = 42 -- Just for fun
  return (a + b + c + k)
answered 2010-09-04T18:21:18.163
8

Examples for "maybe":

> maybe 0 (+ 42) Nothing
0
> maybe 0 (+ 42) (Just 12)
54
answered 2010-09-06T09:25:31.550

Your Answer