Haskell/Libraries/Maybe

The  data is used with functions that might be unsuccessful. The full description is in Maybe monad chapter.

Definition
The Standard Prelude defines the  type as follows:

Recall that the type a is polymorphic and can contain complex types or even other monads (such as IO types).

Library functions
The module, in the standard hierarchical libraries, contains a wealth of functions for working with Maybe values.

Querying
Two obvious functions give you information about a Maybe value:

returns True if when given an argument in the form.

returns True if its argument is.

Getting out
There are a handful of functions for converting Maybe values to non-Maybe values.

applies a given function to the internal value passed by a  but otherwise returns a default value when given.

We might want to use  without applying any function to the. We can do that by calling  with the function. already has this as :

Note the use of point-free style. evaluates to a function that is ready to take a  value.

Lists and Maybe
The many similarities between lists and  are discussed in the List monad chapter. Given the connections, there are a couple of functions for converting between one and the other:

Failed computations return  for lists and   for Maybe. converts from the list to the Maybe monad. As  can only hold one value,   only takes the first solution from a list.

The reverse  is, of course,  :

Lists manipulation
There are a couple of functions which are analogues of the normal Prelude list manipulation functions but are specialized to Maybe values.

Continue on some failures
We might want an OR function that won't make a whole computation fail just because one part failed.

Given a list of Maybe values,  extracts all the values in the form , and strips off the   constructors. List comprehension does the job here (as we showed in the pattern matching chapter):

applies a function to a list and collects the successes. It can be understood as a composition of functions you already know:

However, the actual definition in  traverses the list is potentially more efficient:

Stop on failure
Rather than OR, we might want to collect values if and only if all succeed.