The Haskell 1.4 Library Report
top | back | next | contents

8  Maybe Utilities


module Maybe(
    isJust, fromJust, fromMaybe, listToMaybe, maybeToList,
    catMaybes, mapMaybe, unfoldr ) where

isJust               :: Maybe a -> Bool
fromJust             :: Maybe a -> a
fromMaybe            :: a -> Maybe a -> a
listToMaybe          :: [a] -> Maybe a
maybeToList          :: Maybe a -> [a]
findMaybe            :: (a -> Bool) -> [a] -> Maybe a
catMaybes            :: [Maybe a] -> [a]
mapMaybe             :: (a -> Maybe b) -> [a] -> [b]
unfoldr              :: (a -> Maybe (b, a)) -> a -> (a,[b])

The type constructor Maybe is defined in Prelude as

data Maybe a = Nothing | Just a

The purpose of the Maybe type is to provide a method of dealing with illegal or optional values without terminating the program, as would happen if error were used, and without using IOError from the IO monad, which would cause the expression to become monadic. A correct result is encapsulated by wrapping it in Just; an incorrect result is returned as Nothing.

Most of the functions from this module are easily understood from the definitions given here. The unfoldr function undoes a foldr operation, returning the original initialiser and list of arguments. Note that, in general, only invertable functions can be unfolded.

unfoldr f' (foldr f z xs) == (z,xs)

if the following holds:

f' (f x y) = Just (x,y)
f' z       = Nothing

Other operations on Maybe are provided as part of the monadic classes in the Prelude.

8.1  Library Maybe


module Maybe(
    isJust, fromJust, fromMaybe, listToMaybe, maybeToList,
    catMaybes, mapMaybe, unfoldr ) where

isJust                 :: Maybe a -> Bool
isJust (Just a)        =  True
isJust Nothing         =  False

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

fromMaybe              :: a -> Maybe a -> a
fromMaybe d Nothing    =  d
fromMaybe d (Just a)   =  a

maybeToList            :: Maybe a -> [a]
maybeToList Nothing    =  []
maybeToList (Just a)   =  [a]

listToMaybe            :: [a] -> Maybe a
listToMaybe []         =  Nothing
listToMaybe (a:_)      =  Just a
 
catMaybes              :: [Maybe a] -> [a]
catMaybes ms           =  [ m | Just m <- ms ]

mapMaybe               :: (a -> Maybe b) -> [a] -> [b]
mapMaybe f             =  catMaybes . map f

unfoldr                :: ([a] -> Maybe ([a], a)) -> [a] -> ([a],[a])
unfoldr f x =
  case f x of
  Just (x',y) -> let (ys,x'') = unfoldr f x' in (x'',y:ys)
  Nothing     -> (x,[])


The Haskell 1.4 Library Report
top | back | next | contents
April 4, 1997