From 3e970f7aa51c69d7e659392120722ebc1611b4d6 Mon Sep 17 00:00:00 2001 From: Matthew Hall Date: Thu, 9 Mar 2023 00:28:39 +1300 Subject: Rewrite Recover in terms of Optional --- src/parcom.cr | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/parcom.cr b/src/parcom.cr index c1eb676..9e90562 100644 --- a/src/parcom.cr +++ b/src/parcom.cr @@ -67,10 +67,12 @@ module Parcom Plus.new(self, other) end + # TODO: allow/change to support block invocation def assert(f : V -> Bool) Assert.new(self, f) end + # TODO: allow/change to support block invocation def map(f : V -> U) : Map(T, V, U) forall U Map.new(self, f) end @@ -116,6 +118,7 @@ module Parcom end end + # TODO: allow/change to support block invocation class Assert(T, V) < Parser(T, V) def initialize(@p : Parser(T, V), @f : V -> Bool) end @@ -131,6 +134,7 @@ module Parcom end end + # TODO: allow/change to support block invocation class Satisfy(T) < Parser(T, T) def initialize(@f : T -> Bool) end @@ -160,6 +164,7 @@ 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) end @@ -197,11 +202,15 @@ module Parcom end class Recover(T, V) < Parser(T, V) - def initialize(@p : Parser(T, V), @default : V) + @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) end def parse(tokens : TokenStream(T)) : Result(T, V) - @p.parse?(tokens) || Result.new(tokens, @default) + @p.parse(tokens) end end -- cgit v1.2.1