liveBook · Manning

Alternative

As explained in Learn Haskell by Example

Alternative is a Haskell type class for applicative computations that support an identity failure value and an associative choice operation.

Alternative extends applicative computations with two ways to represent choice: empty is an identity failure value, and (<|>) tries one computation or another. The operation is associative, so alternatives can be nested and combined predictably. section 12.1.4

For a parser, (<*>) means “parse this and then that,” while (<|>) means “try this, or try that.” If the first parser fails without consuming input, the original input goes to the second parser. The combined parser fails only when both alternatives fail. section 12.1.4

class Applicative f => Alternative f where
  empty :: f a
  (<|>) :: f a -> f a -> f a
  some :: f a -> f [a]
  many :: f a -> f [a]
  {-# MINIMAL empty, (<|>) #-}

The core interface shows the required empty and (<|>) operations, along with some and many for repetition. section 12.1.4

Choosing between parser alternatives

A parser can accept either letter A or letter B: string "A" <|> string "B". Running it on "A" or "B" succeeds; running it on "C" reports both failed alternatives. A custom Parser instance uses empty to fail without consuming input and (<|>) to retry the second parser while combining error messages.

How Learn Haskell by Example covers it

How deep it goes
Explains the interface, parser rollback semantics, error combination, repetition, and collection-wide choice through implementation examples.
Examples
Demonstrates Maybe choices, custom parser alternatives, combined parse errors, repeated strings, spaces, and asum over parser lists.
What it assumes
Assumes familiarity with Functor and Applicative composition while introducing failure choice through Maybe and parser examples.
What you can do after
Build it from scratch by defining empty and (<|>) for a parser, then compose alternatives with some, many, asum, and choice.
How it connects
Connects Alternative with Applicative, Functor, Monad, MonadFail, and MonadPlus through their roles in composing or failing effectful actions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.