- The class definition
- Dining out
- Greeting, polymorphically
many: a stateful loop
- Folding with
- IO: not atomic
- Parsers: sometimes atomic
- STM: always atomic
- MonadZero: Alternative’s predecessor
- The rise of Applicative
No plan of operations extends with any certainty beyond the first contact with the main hostile force.
– Helmuth von Moltke the Elder (Prussian military leader), 1871
Alternative class is all about recovering from failure: try one thing, and if it doesn’t work, try another. Alternatives give our programs ways to adapt to circumstance by choosing from multiple strategies.
This is a kind of monoid! It may look a bit different, because whereas
Monoid is a class of types,
Alternative is a monoidal typeclass for type constructors – a subclass of applicative functors, to be more precise.
mappend might combine values or choose between values, so we often have two viable monoids over a single type, the
Alternative class specifically represents monoids of choice. It is, therefore, most analogous to
Monoids such as
Once you understand what
Alternative means, it is typically easy to guess how each type’s instance will behave;
Alternative does not give rise to the sort of proliferation of newtypes that
Monoid does. Lists, however, still have two
Alternatives: one represents concatenation and the other, via the
newtype, represents choice between two lists.
We discuss quite a few
Alternative functors below. The most common practically interesting instances are
STM, and various types of parsers.