From 8f8bee2893df280bd013e06c338838c758c4d8fc Mon Sep 17 00:00:00 2001 From: Matthew Hall Date: Thu, 9 Mar 2023 00:57:22 +1300 Subject: Rewrite Map to use blocks --- src/parcom.cr | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'src/parcom.cr') diff --git a/src/parcom.cr b/src/parcom.cr index 3aed672..de88a31 100644 --- a/src/parcom.cr +++ b/src/parcom.cr @@ -75,9 +75,12 @@ module Parcom Assert.new(self, &block) end - # TODO: allow/change to support block invocation + def map(&block : V -> U) : Map(T, V, U) forall U + Map.new(self, &block) + end + def map(f : V -> U) : Map(T, V, U) forall U - Map.new(self, f) + Map.new(self, &f) end def recover(default : V) : Recover(T, V) @@ -167,9 +170,9 @@ module Parcom end end - # TODO: allow/change to support block invocation class Map(T, V, U) < Parser(T, U) - def initialize(@p : Parser(T, V), @f : V -> U) + def initialize(@p : Parser(T, V), &block : V -> U) + @f = block end def parse(tokens : TokenStream(T)) : Result(T, U) @@ -182,8 +185,7 @@ module Parcom @p : Map(T, {V, Nil}, V) def initialize(p : Parser(T, V)) - f = ->(tup : {V, Nil}) { tup[0] } - @p = (p + Eof(T).new).map(f) + @p = (p + Eof(T).new).map &.first end def parse(tokens : TokenStream(T)) : Result(T, V) @@ -206,8 +208,7 @@ module Parcom @p : Map(T, V?, V) def initialize(p : Parser(T, V), default : V) - f = ->(x : V?) { x.nil? ? default : x } - @p = Optional.new(p).map(f) + @p = Optional.new(p).map { |x| x.nil? ? default : x } end def parse(tokens : TokenStream(T)) : Result(T, V) -- cgit v1.2.1