diff options
| -rw-r--r-- | spec/parcom_spec.cr | 12 | ||||
| -rw-r--r-- | src/parcom/parser.cr | 12 |
2 files changed, 24 insertions, 0 deletions
diff --git a/spec/parcom_spec.cr b/spec/parcom_spec.cr index efb3964..cee6ff4 100644 --- a/spec/parcom_spec.cr +++ b/spec/parcom_spec.cr @@ -278,6 +278,18 @@ describe Parser do end end + describe "#map_const" do + p = Parser(Char, Char).any_token + p_mapped = p.map_const(42) + + tokens = Tokens.from_string("abcd") + result = p_mapped.parse(tokens) + + it "changes the value of the result" do + result.value.should eq(42) + end + end + describe "#|" do a = Parser(Char, Char).token('a') b = Parser(Char, Char).token('b') diff --git a/src/parcom/parser.cr b/src/parcom/parser.cr index fd161f9..57c7b44 100644 --- a/src/parcom/parser.cr +++ b/src/parcom/parser.cr @@ -207,6 +207,18 @@ module Parcom map(block) end + # Replaces the value inside `self` when parsing is successful. + # This is effectively a shorthand for the following: + # ``` + # a = Parser.token('a') + # # These are equivalent: + # into42_map = a.map { |_| 42 } + # into42_map_const = a.map_const(42) + # ``` + def map_const(value : V) : Parser(T, V) forall V + map { |_| value }.named("#{@name} (const #{value})") + end + # Creates a new parser from `self` and another parser that will # try to parse with either of them. If the first parser succeeds, # it will return the result of the first parser. Otherwise, it will |
