From b274828831fec26cd8b3089ffef14cb96ce2de2f Mon Sep 17 00:00:00 2001 From: Matthew Hall Date: Thu, 16 Mar 2023 20:36:03 +1300 Subject: Second rewrite attempt, this one should work, monkaS --- src/__OLD_parcom/map.cr | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/__OLD_parcom/map.cr (limited to 'src/__OLD_parcom/map.cr') diff --git a/src/__OLD_parcom/map.cr b/src/__OLD_parcom/map.cr new file mode 100644 index 0000000..34961b5 --- /dev/null +++ b/src/__OLD_parcom/map.cr @@ -0,0 +1,30 @@ +require "./parser.cr" + +module Parcom + # `Map` is a `Parser` that tries to parse using another parser, + # and then changing the result of that parser to a different value. + # + # Example: + # ``` + # # Where `Digits` is some parser that returns an array of digit characters + # parse_i32 = Digits.new.map { |x| x.join.to_i32 } + # result = parse_i32.parse(Tokens.from_string("1234")) + # result.value # => 1234 (Int32) + # ``` + class Map(T, V, U) < Parser(T, U) + # Accepts the parser to use and the function to apply to the result. + def initialize(@p : Parser(T, V), &block : V -> U) + @f = block + end + + # Tries to parse with the given parser and applies the + # function to the result if successful. + def parse(tokens : Tokens(T)) : Result(T, U) + result = @p.parse(tokens) + Result.new(result.tokens, @f.call(result.value)) + rescue ex : ParserFail + raise ParserFail.new("Map: #{ex.message}") + end + end +end + -- cgit v1.2.1