@@ -5,6 +5,7 @@ import Builtins
55import Prelude.Basics
66import Prelude.Bool
77import Prelude.Classes
8+import Prelude.Foldable
89import Prelude.Functor
910
1011---- Applicative functors/Idioms
@@ -48,3 +49,26 @@ guard a = if a then pure () else empty
4849when : Applicative f => Bool -> Lazy (f ()) -> f ()
4950when True f = Force f
5051when False f = pure ()
52+
53+||| Fold using Alternative
54+|||
55+||| If you have a left-biased alternative operator `<|>`, then `choice`
56+||| performs left-biased choice from a list of alternatives, which means that
57+||| it evaluates to the left-most non-`empty` alternative.
58+|||
59+||| If the list is empty, or all values in it are `empty`, then it
60+||| evaluates to `empty`.
61+|||
62+||| Example:
63+|||
64+||| ```
65+||| -- given a parser expression like:
66+||| expr = literal <|> keyword <|> funcall
67+|||
68+||| -- choice lets you write this as:
69+||| expr = choice [literal, keyword, funcall]
70+||| ```
71+|||
72+||| Note: In Haskell, `choice` is called `asum`.
73+choice : (Foldable t, Alternative f) => t (f a) -> f a
74+choice x = foldr (<|>) empty x