liveBook · Manning

Asum

As explained in Learn Haskell by Example

asum is a Haskell function that combines a foldable collection of alternative applicative computations using Alternative choice semantics.

asum combines a foldable collection of alternative applicative computations, trying them in order with Alternative's (<|>) choice semantics. Its type is asum :: (Foldable t, Alternative f) => t (f a) -> f a. section 12.1.4

Use asum when a list of alternatives is clearer than a long chain of (<|>):

  • Provide parsers or other Alternative computations in a foldable structure. section 12.1.4
  • Preserve order: the first successful alternative supplies the result. section 12.1.4
  • Expect empty as the final identity case when every alternative fails; custom parsers can expose that failure in their error message. section 12.1.4

Choosing between string parsers

choice :: [Parser a] -> Parser a choice = asum runParser (asum [string "A", string "B"]) "A" -- Right ("", "A") runParser (asum [string "A", string "B"]) "C" -- failure mentioning both alternatives and empty alternative 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, (<|>) #-}

Inspect Alternative's empty and (<|>) operations to see the primitives that determine asum's behavior. section 12.1.4

How Learn Haskell by Example covers it

How deep it goes
Defines the type and folding behavior, then demonstrates parser results and the empty identity case.
Examples
Uses string parsers for A and B, a custom choice alias, and failures that include empty alternative.
What it assumes
Assumes familiarity with Haskell types, parsers, Applicative, and Alternative choice operations.
What you can do after
Apply it via Data.Foldable to express ordered parser choices compactly and interpret their failure behavior.
How it connects
Connects Foldable collections with Alternative choice, Applicative computations, parsers, and (<|>).

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.