How to get the value of a Maybe in Haskell

Moe picture Moe · Feb 9, 2011 · Viewed 36k times · Source

I'm relatively new to Haskell and began to read "Real World Haskell".

I Just stumbled over the type Maybe and have a question about how to receive the actual value from a Just 1 for example.

I have written the following code:

combine a b c = (eliminate a, eliminate b, eliminate c)
                where eliminate (Just a) = a
                      eliminate Nothing = 0

This works fine if I use:

combine (Just 1) Nothing (Just 2)

But if I change, for example, 1 to a String it doesn't work.

I think I know why: because eliminate has to give back one type, which is, in this case, an Int. But how can I change eliminate to deal at least with Strings (or maybe with all kind of types)?

Answer

ephemient picture ephemient · Feb 9, 2011

From the standard Prelude,

maybe :: b -> (a -> b) -> Maybe a -> b
maybe n _ Nothing = n
maybe _ f (Just x) = f x

Given a default value, and a function, apply the function to the value in the Maybe or return the default value.

Your eliminate could be written maybe 0 id, e.g. apply the identity function, or return 0.

From the standard Data.Maybe,

fromJust :: Maybe a -> a
fromJust Nothing = error "Maybe.fromJust: Nothing"
fromJust (Just x) = x

This is a partial function (does not return a value for every input, as opposed to a total function, which does), but extracts the value when possible.