Safe Haskell | Safe |
---|---|

Language | Haskell2010 |

# The `Maybe`

type and operations

data Maybe a :: * -> *

The `Maybe`

type encapsulates an optional value. A value of type

either contains a value of type `Maybe`

a`a`

(represented as

),
or it is empty (represented as `Just`

a`Nothing`

). Using `Maybe`

is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as `error`

.

The `Maybe`

type is also a monad. It is a simple kind of error
monad, where all errors are represented by `Nothing`

. A richer
error monad can be built using the `Either`

type.

listToMaybe :: [a] -> Maybe a

The `listToMaybe`

function returns `Nothing`

on an empty list
or

where `Just`

a`a`

is the first element of the list.

maybeToList :: Maybe a -> [a]

The `maybeToList`

function returns an empty list when given
`Nothing`

or a singleton list when not given `Nothing`

.

# Specification

module Data.Maybe( Maybe(Nothing, Just), isJust, isNothing, fromJust, fromMaybe, listToMaybe, maybeToList, catMaybes, mapMaybe, maybe ) where maybe :: b -> (a -> b) -> Maybe a -> b maybe n _ Nothing = n maybe _ f (Just x) = f x isJust :: Maybe a -> Bool isJust (Just a) = True isJust Nothing = False isNothing :: Maybe a -> Bool isNothing = not . isJust 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