Alternative

Contents
  • The class definition
  • Maybe
    • Greeting
  • ZipList
  • Lists
    • Dining out
    • Greeting
  • Greeting, polymorphically
  • many: a stateful loop
  • IO
    • Failure
    • State
  • Parsing
  • Laws
  • Folding with asum
  • Quasirings?
    • IO: not atomic
    • Parsers: sometimes atomic
    • STM: always atomic
  • Alternative and Monoid
  • History
    • MonadZero: Alternative’s predecessor
    • The rise of Applicative
    • many and some

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

The 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.

Unlike Monoid, where 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 First and Any.

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 ZipList newtype, represents choice between two lists.

We discuss quite a few Alternative functors below. The most common practically interesting instances are Maybe, STM, and various types of parsers.

Join Type Classes for courses and projects to get you started and make you an expert in FP with Haskell.