tags:

views:

195

answers:

5

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.

+2  A: 

Sorry, I should have googled better.

using the fromMaybe function is exactly what I need. fromMaybe will return the value in Maybe if it is not nothing, otherwise it will return a default value supplied to fromMaybe.

http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Maybe.html

dpsthree
Yeah but make sure that is the behaviour that you want, because if you are going to, for example, use a Maybe Int and then every time that it is Nothing you return zero then you should have just used a plain old Int right from the start. Maybe is supposed to help encode the absence of a result or value and not really supposed to be worked around. Personally I try to steer as clear of the fromMaybe function.
Robert Massaioli
+6  A: 

You could use Data.Maybe.fromMaybe, which takes a Maybe a and a value to use if it is Nothing. You could use the unsafe Data.Maybe.fromJust, which will just crash if the value is Nothing. You likely want to keep things in the Maybe monad. If you wanted to add an integer in a maybe, you could do something like

import Control.Applicative

f x = (+x) <$> Just 4

which is the same as f x = fmap (+x) (Just 4)

f 3 will then be Just 7. (You can continue to chain additional computations in this manner.)

arsenm
`f 3` will be `Just 7`, not `7`.
Yitz
Edited accordingly.
jrockway
+4  A: 

Alternatively you can pattern match:

case maybeValue of
  Just value -> ...
  Nothing    -> ...
Martijn
This was more like what I was trying to do than the answer I had found. Thanks
dpsthree
+3  A: 

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)
Dario
you mean `a + b + c + k`?
KennyTM
He did. Edited :)
jrockway
:P true, thanks^^
Dario
+1  A: 

Examples for "maybe":

> maybe 0 (+ 42) Nothing
0
> maybe 0 (+ 42) (Just 12)
54
Lenny222