on master help sign in
Merge pull request #2524 from jeremy-w/choice-docs
d9bfa3eDavid Christiansen
libs/prelude/Prelude/Applicative.idr+24
@@ -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
9
10
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 ()
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