How to get the value of a Maybe in Haskell

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)