aboutsummaryrefslogtreecommitdiff
path: root/src/__OLD_parcom/between.cr
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-16 20:36:03 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-16 20:36:03 +1300
commitb274828831fec26cd8b3089ffef14cb96ce2de2f (patch)
treeff5927b85a59b4d85c9e4aa269a475a7a37a54a0 /src/__OLD_parcom/between.cr
parent77c370d27be174e0b036b33d1469e84e67a7153a (diff)
Second rewrite attempt, this one should work, monkaS
Diffstat (limited to 'src/__OLD_parcom/between.cr')
-rw-r--r--src/__OLD_parcom/between.cr37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/__OLD_parcom/between.cr b/src/__OLD_parcom/between.cr
new file mode 100644
index 0000000..05519e4
--- /dev/null
+++ b/src/__OLD_parcom/between.cr
@@ -0,0 +1,37 @@
+require "./parser.cr"
+require "./map.cr"
+require "./exactly.cr"
+require "./at_most.cr"
+
+module Parcom
+ # `Between` is a `Parser` that tries to parse with another parser a number
+ # of times within a specified range. The results of each successful parse
+ # are returned in an array. If the number of successful parses is out of
+ # the lower bound of the range, the parser fails. If the number of successful
+ # parses reaches thhe upper bound of the range, the parsing stops, even if it
+ # is possible to keep parsing.
+ class Between(T, V) < Parser(T, Array(V))
+ @p : Map(T, {Array(V), Array(V)}, Array(V))
+
+ # Accepts the lower and upper bounds for the number of parsing attempts,
+ # as well as the parser to use. This method works the same way whether or
+ # not the larger value is passed first or second. If a negative int value
+ # is given for either parameter, it is treated as `0`.
+ # TODO: Overload to allow for Range objects.
+ def initialize(i : Int, j : Int, p : Parser(T, V))
+ lower = i < j ? i : j
+ upper = (i - j).abs
+ @p = (Exactly.new(lower, p) + AtMost.new(upper, p)).map do |tup|
+ tup[0] + tup[1]
+ end
+ end
+
+ # Tries to parse a numebr of times within the given range.
+ def parse(tokens : Tokens(T)) : Result(T, Array(V))
+ @p.parse(tokens)
+ rescue ex : ParserFail
+ raise ParserFail.new("Between: #{ex.message}")
+ end
+ end
+end
+