Module DA.Optional¶
The Optional type encapsulates an optional value. A value of type
Optional a either contains a value of type a (represented as Some a),
or it is empty (represented as None). Using Optional is a good way
to deal with errors or exceptional cases without resorting to
drastic measures such as error.
The Optional type is also an action. It is a simple kind of error
action, where all errors are represented by None. A richer
error action can be built using the Either type.
Functions¶
- fromSome
: Optional a -> a
The
fromSomefunction extracts the element out of aSomeand throws an error if its argument isNone.Note that in most cases you should prefer using
fromSomeNoteto get a better error on failures.
- fromSomeNote
-
Like
fromSomebut with a custom error message.
- catOptionals
: [Optional a] -> [a]
The
catOptionalsfunction takes a list ofOptionalsand returns a list of all theSomevalues.
- listToOptional
: [a] -> Optional a
The
listToOptionalfunction returnsNoneon an empty list orSomea where a is the first element of the list.
- optionalToList
: Optional a -> [a]
The
optionalToListfunction returns an empty list when givenNoneor a singleton list when not givenNone.
- fromOptional
: a -> Optional a -> a
The
fromOptionalfunction takes a default value and aOptionalvalue. If theOptionalisNone, it returns the default values otherwise, it returns the value contained in theOptional.
- mapOptional
: (a -> Optional b) -> [a] -> [b]
The
mapOptionalfunction is a version ofmapwhich can throw out elements. In particular, the functional argument returns something of typeOptional b. If this isNone, no element is added on to the result list. If it isSome b, thenbis included in the result list.
- whenSome
: Applicative m => Optional a -> (a -> m ()) -> m ()
Perform some operation on
Some, given the field inside theSome.
- findOptional
: (a -> Optional b) -> [a] -> Optional b
The
findOptionalreturns the value of the predicate at the first element where it returnsSome.findOptionalis similar tofindbut it allows you to return a value from the predicate. This is useful both as a more type safe version if the predicate corresponds to a pattern match and for performance to avoid duplicating work performed in the predicate.