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
