diff options
| author | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-13 20:41:57 +1300 |
|---|---|---|
| committer | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-13 20:41:57 +1300 |
| commit | 77c370d27be174e0b036b33d1469e84e67a7153a (patch) | |
| tree | af3b19aacfc571415ac4dad560a6e187d613cf43 | |
| parent | 2f5521ae6a0b5897a6970379d353047281d3a909 (diff) | |
Documentation for SepBy
| -rw-r--r-- | src/parcom.cr | 16 | ||||
| -rw-r--r-- | src/parcom/sep_by.cr | 38 |
2 files changed, 38 insertions, 16 deletions
diff --git a/src/parcom.cr b/src/parcom.cr index 8c55014..ddb2e50 100644 --- a/src/parcom.cr +++ b/src/parcom.cr @@ -80,21 +80,5 @@ module Parcom def initialize(@tokens : Tokens(T), @value : V) end end - - class SepBy(T, V, U) < Parser(T, Array(V)) - @p : Map(T, {V, Array(V)}, Array(V)) - - def initialize(elem : Parser(T, V), sep : Parser(T, U)) - @p = (elem + Many(T, U).new(sep >> elem)).map do |tup| - [tup[0]] + tup[1] - end - end - - def parse(tokens : Tokens(T)) : Result(T, Array(V)) - @p.parse(tokens) - rescue ex : ParserFail - raise ParserFail.new("SepBy: #{ex.message}") - end - end end diff --git a/src/parcom/sep_by.cr b/src/parcom/sep_by.cr new file mode 100644 index 0000000..fa19027 --- /dev/null +++ b/src/parcom/sep_by.cr @@ -0,0 +1,38 @@ +require "./parser.cr" +require "./map.cr" +require "./many.cr" + +module Parcom + # `SepBy` is a `Parser` that tries to parse one or more times with one + # parser, alternating with a second parser. + # + # Example: + # ``` + # letter_a = Token.new('a') + # letter_b = Token.new('b') + # p = SepBy(Char, Car, Char).new(letter_a, letter_b) + # tokens = Tokens.from_string("ababababa") + # + # result = p.parse(tokens) + # puts result.value # => ['a', 'a', 'a', 'a', 'a'] + # ``` + class SepBy(T, V, U) < Parser(T, Array(V)) + @p : Map(T, {V, Array(V)}, Array(V)) + + # Accepts the parser that parses the result values, and the + # parser that parses the sepatators. + def initialize(elem : Parser(T, V), sep : Parser(T, U)) + @p = (elem + Many(T, U).new(sep >> elem)).map do |tup| + [tup[0]] + tup[1] + end + end + + # Tries to parse, alternating the first and second parsers. + def parse(tokens : Tokens(T)) : Result(T, Array(V)) + @p.parse(tokens) + rescue ex : ParserFail + raise ParserFail.new("SepBy: #{ex.message}") + end + end +end + |
