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

Language | Haskell2010 |

# Documentation

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.

Monad Maybe | |

Functor Maybe | |

MonadFix Maybe | |

Applicative Maybe | |

Foldable Maybe | |

Traversable Maybe | |

Generic1 Maybe | |

Eq1 Maybe | |

Ord1 Maybe | |

Read1 Maybe | |

Show1 Maybe | |

Alternative Maybe | |

MonadPlus Maybe | |

Eq a => Eq (Maybe a) | |

Ord a => Ord (Maybe a) | |

Generic (Maybe a) | |

Semigroup a => Semigroup (Maybe a) | |

Monoid a => Monoid (Maybe a) | Lift a semigroup into |

Lift a => Lift (Maybe a) | |

SingI (Maybe a) (Nothing a) | |

SingKind a (KProxy a) => SingKind (Maybe a) (KProxy (Maybe a)) | |

SingI a a1 => SingI (Maybe a) (Just a a1) | |

type Rep1 Maybe | |

type Rep (Maybe a) | |

data Sing (Maybe a) | |

type (==) (Maybe k) a b | |

type DemoteRep (Maybe a) (KProxy (Maybe a)) | |

maybe :: b -> (a -> b) -> Maybe a -> b #

The `maybe`

function takes a default value, a function, and a `Maybe`

value. If the `Maybe`

value is `Nothing`

, the function returns the
default value. Otherwise, it applies the function to the value inside
the `Just`

and returns the result.

#### Examples

Basic usage:

`>>>`

True`maybe False odd (Just 3)`

`>>>`

False`maybe False odd Nothing`

Read an integer from a string using `readMaybe`

. If we succeed,
return twice the integer; that is, apply `(*2)`

to it. If instead
we fail to parse an integer, return `0`

by default:

`>>>`

`import Text.Read ( readMaybe )`

`>>>`

10`maybe 0 (*2) (readMaybe "5")`

`>>>`

0`maybe 0 (*2) (readMaybe "")`

Apply `show`

to a `Maybe Int`

. If we have `Just n`

, we want to show
the underlying `Int`

`n`

. But if we have `Nothing`

, we return the
empty string instead of (for example) "Nothing":

`>>>`

"5"`maybe "" show (Just 5)`

`>>>`

""`maybe "" show Nothing`

fromMaybe :: a -> Maybe a -> a #

The `fromMaybe`

function takes a default value and and `Maybe`

value. If the `Maybe`

is `Nothing`

, it returns the default values;
otherwise, it returns the value contained in the `Maybe`

.

#### Examples

Basic usage:

`>>>`

"Hello, World!"`fromMaybe "" (Just "Hello, World!")`

`>>>`

""`fromMaybe "" Nothing`

Read an integer from a string using `readMaybe`

. If we fail to
parse an integer, we want to return `0`

by default:

`>>>`

`import Text.Read ( readMaybe )`

`>>>`

5`fromMaybe 0 (readMaybe "5")`

`>>>`

0`fromMaybe 0 (readMaybe "")`