@@ -5,6 +5,7 @@ import Builtins
5import Prelude.Basics
5import Prelude.Basics
6import Prelude.Bool
6import Prelude.Bool
7import Prelude.Classes
7import Prelude.Classes
8+import Prelude.Foldable
8import Prelude.Functor
9import Prelude.Functor
10---- Applicative functors/Idioms
11---- Applicative functors/Idioms
@@ -48,3 +49,26 @@ guard a = if a then pure () else empty
48when : Applicative f => Bool -> Lazy (f ()) -> f ()
49when : Applicative f => Bool -> Lazy (f ()) -> f ()
49when True f = Force f
50when True f = Force f
50when False f = pure ()
51when False f = pure ()
53+||| Fold using Alternative
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.
59+||| If the list is empty, or all values in it are `empty`, then it
60+||| evaluates to `empty`.
65+||| -- given a parser expression like:
66+||| expr = literal <|> keyword <|> funcall
68+||| -- choice lets you write this as:
69+||| expr = choice [literal, keyword, funcall]
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