Maybe
From HaskellWiki
BrettGiles (Talk | contribs) (Adding a page for the lovely Maybe type.) |
m (fix) |
||
Line 1: | Line 1: | ||
− | {{Standard type|Maybe|module=Data.Maybe|module-doc=Control-Maybe|package=base}} |
+ | {{Standard type|Maybe|module=Data.Maybe|module-doc=Data-Maybe|package=base}} |
The '''Maybe''' type is defined as follows: |
The '''Maybe''' type is defined as follows: |
||
Revision as of 02:51, 6 March 2006
import Data.Maybe |
The Maybe type is defined as follows:
data Maybe a = Just a | Nothing deriving (Eq, Ord)
It allows the programmer to specify something may not be there.
Contents |
1 Type Equation
Maybe satisfies the type equation FX = 1 + FX, where the functor F takes a set to a point plus that set.
2 Comparison to imperative languages
Most imperative languages will ignore this, or allow one to use NULL (defined in some manner) to specify a value might not be there.
3 Classes
As one can see from the type definition, Maybe will be an instance of Eq and Ord when the base type is. As well, instances of Functor and Monad are defined for Maybe.
For Functor, the fmap
function moves inside the Just constructor and is identity on the Nothing constructor.
For Monad, the bind operation passes through Just, while Nothing will force the result to always be Nothing.
3.1 Usage example
Using the Monad class definition can lead to much more compact code. For example:
f::Int -> Maybe Int f 0 = Nothing f x = Just x
g :: Int -> Maybe Int g 100 = Nothing g x = Just x
h ::Int -> Maybe Int h x = case f x of Just n -> g n Nothing -> Nothing h' :: Int -> Maybe Int h' x = do n <- f x g n
The functions h
and h'
will give the same results. (). In this case the savings in code size is quite modest, stringing together multiple functions like f
and g
will be more noticeable.