Go to the first, previous, next, last section, table of contents.

The `Maybes' type

The `Maybe' type is in the Haskell 1.4 prelude. Moreover, the required `Maybe' library provides many useful functions on `Maybe's. This (pre-1.3) module provides some more: An `Either'-like type called `MaybeErr':
data MaybeErr val err = Succeeded val | Failed err
Some operations to do with `Maybe' (some commentary follows):
maybeToBool :: Maybe a -> Bool      -- Nothing => False; Just => True
allMaybes   :: [Maybe a] -> Maybe [a]
firstJust   :: [Maybe a] -> Maybe a
findJust    :: (a -> Maybe b) -> [a] -> Maybe b

assocMaybe  :: Eq a => [(a,b)] -> a -> Maybe b
mkLookupFun :: (key -> key -> Bool) -- Equality predicate
            -> [(key,val)]          -- The assoc list
            -> (key -> Maybe val)   -- A lookup fun to use
mkLookupFunDef :: (key -> key -> Bool)  -- Equality predicate
               -> [(key,val)]           -- The assoc list
               -> val                   -- Value to return on failure
               -> key                   -- The key
               -> val                   -- The corresponding value

    -- a monad thing
thenMaybe   :: Maybe a -> (a -> Maybe b) -> Maybe b
returnMaybe :: a -> Maybe a
failMaybe   :: Maybe a
mapMaybe    :: (a -> Maybe b) -> [a] -> Maybe [b]
NB: `catMaybes' which used to be here, is now available via the standard `Maybe' interface (`Maybe' is an instance of `MonadPlus'). `allMaybes' collects a list of `Justs' into a single `Just', returning `Nothing' if there are any `Nothings'. `firstJust' takes a list of `Maybes' and returns the first `Just' if there is one, or `Nothing' otherwise. `assocMaybe' looks up in an association list, returning `Nothing' if it fails. Now, some operations to do with `MaybeErr' (comments follow):
    -- a monad thing (surprise, surprise)
thenMaB   :: MaybeErr a err -> (a -> MaybeErr b err) -> MaybeErr b err
returnMaB :: val -> MaybeErr val err
failMaB   :: err -> MaybeErr val err

listMaybeErrs :: [MaybeErr val err] -> MaybeErr [val] [err]
foldlMaybeErrs :: (acc -> input -> MaybeErr acc err)
               -> acc
               -> [input]
               -> MaybeErr acc [err]
`listMaybeErrs' takes a list of `MaybeErrs' and, if they all succeed, returns a `Succeeded' of a list of their values. If any fail, it returns a `Failed' of the list of all the errors in the list. `foldlMaybeErrs' works along a list, carrying an accumulator; it applies the given function to the accumulator and the next list item, accumulating any errors that occur.
Go to the first, previous, next, last section, table of contents.