on master help sign in
Text.Lexer, Text.Parser: add `choiceMap`
commit59ac46373ba333295a9a4f14d41d655b62553132 authorMichael Morgan <morgan.michael@me.com> dateSat 28 Oct 2017, 12:46 (9 years ago) parent8656531
2 files changed+28−9
libs/contrib/Text/Lexer.idr+15−4 libs/contrib/Text/Parser.idr+13−5
libs/contrib/Text/Lexer.idr+15−4
@@ -1,5 +1,7 @@
11module Text.Lexer
22
3+import Data.Bool.Extra
4+
35import public Text.Lexer.Core
46
57%default total
@@ -18,10 +20,19 @@ opt l = l <|> empty
1820non : (l : Lexer) -> Lexer
1921non l = reject l <+> any
2022
21−||| Recognise the first matching lexer in a container. Always consumes input
22−||| if an option succeeds. Fails if the container is empty.
23−choice : Foldable t => t Lexer -> Lexer
24−choice xs = foldr (<|>) fail xs
23+||| Produce recognisers by applying a function to elements of a container, and
24+||| recognise the first match. Consumes input if the function produces consuming
25+||| recognisers. Fails if the container is empty.
26+choiceMap : {c : Bool} ->
27+ Foldable t => (a -> Recognise c) -> t a -> Recognise c
28+choiceMap {c} f xs = foldr (\x, acc => rewrite sym (andSameNeutral c) in
29+ f x <|> acc)
30+ fail xs
31+
32+||| Recognise the first matching recogniser in a container. Consumes input if
33+||| recognisers in the list consume. Fails if the container is empty.
34+choice : Foldable t => t (Recognise c) -> Recognise c
35+choice = choiceMap id
2536
2637||| Sequence a list of recognisers. Guaranteed to consume input if the list is
2738||| non-empty and the recognisers consume.
libs/contrib/Text/Parser.idr+13−5
@@ -29,14 +29,22 @@ choose : (l : Grammar tok c1 a) ->
2929 Grammar tok (c1 && c2) (Either a b)
3030choose l r = map Left l <|> map Right r
3131
32+||| Produce a grammar by applying a function to each element of a container,
33+||| then try each resulting grammar until the first one succeeds. Fails if the
34+||| container is empty.
35+choiceMap : {c : Bool} ->
36+ (a -> Grammar tok c b) ->
37+ Foldable t => t a ->
38+ Grammar tok c b
39+choiceMap {c} f xs = foldr (\x, acc => rewrite sym (andSameNeutral c) in
40+ f x <|> acc)
41+ (fail "No more options") xs
42+
3243||| Try each grammar in a container until the first one succeeds.
3344||| Fails if the container is empty.
34−choice : {c : Bool} ->
35− Foldable t => t (Grammar tok c a) ->
45+choice : Foldable t => t (Grammar tok c a) ->
3646 Grammar tok c a
37−choice {c} xs = foldr (\x, acc => rewrite sym (andSameNeutral c) in
38− x <|> acc)
39− (fail "No more options") xs
47+choice = choiceMap id
4048
4149mutual
4250 ||| Parse one or more things