From 0f58d020b54fe59aa76c66788000d47bb7baec2a Mon Sep 17 00:00:00 2001 From: Matthew Hall Date: Thu, 30 Mar 2023 22:24:11 +1300 Subject: Re-implement sep_by in terms of and_then --- src/parcom/parser.cr | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/parcom/parser.cr b/src/parcom/parser.cr index d13219d..7a06f53 100644 --- a/src/parcom/parser.cr +++ b/src/parcom/parser.cr @@ -303,6 +303,7 @@ module Parcom values = [] of U r = self.parse?(tokens) until r.nil? + # Stop if the parser didn't consume any input break unless tokens != r.tokens tokens = r.tokens values << r.value @@ -439,9 +440,10 @@ module Parcom # instance of `self`. It will succeed if it can parse an instance of `self` # that is not followed by any `sep` instances. def sep_by(sep : Parser(T, _)) : Parser(T, Array(U)) - (self + (sep >> self).many).map do |head, tail| - tail.unshift(head) - end.named("<#{@name}> sep by <#{sep.name}>") + parser_chain "<#{@name}> sep by <#{sep.name}>", T, Array(U), + {head, self}, + {tail, (sep >> self).many}, + finally: Parser(T, Array(U)).pure(tail.unshift(head)) end end end -- cgit v1.2.1