aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-13 19:52:52 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-13 19:52:52 +1300
commit2fd2348affc3f571f70aeaf212d1a8054bbbd79f (patch)
tree2e5027120c6a7a086ae8bee1feb1658e702dd4f4
parentf6fe7980390fb9af67a207fd89abee05ed951397 (diff)
Documentation for AtLeast
-rw-r--r--src/parcom.cr16
-rw-r--r--src/parcom/at_least.cr29
2 files changed, 29 insertions, 16 deletions
diff --git a/src/parcom.cr b/src/parcom.cr
index 2e2d417..cc123fd 100644
--- a/src/parcom.cr
+++ b/src/parcom.cr
@@ -81,22 +81,6 @@ module Parcom
end
end
- class AtLeast(T, V) < Parser(T, Array(V))
- @p : Map(T, {Array(V), Array(V)}, Array(V))
-
- def initialize(i : Int, p : Parser(T, V))
- @p = (Exactly.new(i, p) + Many.new(p)).map do |tup|
- tup[0] + tup[1]
- end
- end
-
- def parse(tokens : Tokens(T)) : Result(T, Array(V))
- @p.parse(tokens)
- rescue ex : ParserFail
- raise ParserFail.new("AtLeast: #{ex.message}")
- end
- end
-
class AtMost(T, V) < Parser(T, Array(V))
@p : Map(T, Array(V?), Array(V))
diff --git a/src/parcom/at_least.cr b/src/parcom/at_least.cr
new file mode 100644
index 0000000..2fb8dcf
--- /dev/null
+++ b/src/parcom/at_least.cr
@@ -0,0 +1,29 @@
+require "./parser.cr"
+require "./map.cr"
+require "./exactly.cr"
+
+module Parcom
+ # `AtLeast` is a `Parser` that tries to parser with another parser
+ # a specific number of times. The results of each successful parse
+ # are returned in an array. If the number of successes is less than
+ # the specified number, the parser fails.
+ class AtLeast(T, V) < Parser(T, Array(V))
+ @p : Map(T, {Array(V), Array(V)}, Array(V))
+
+ # Accepts the number of parsing attempts, and the parser to use.
+ # If a negative int is given, it is treated as if it were 0.
+ def initialize(i : Int, p : Parser(T, V))
+ @p = (Exactly.new(i, p) + Many.new(p)).map do |tup|
+ tup[0] + tup[1]
+ end
+ end
+
+ # Tries to parse the given number of times, or more.
+ def parse(tokens : Tokens(T)) : Result(T, Array(V))
+ @p.parse(tokens)
+ rescue ex : ParserFail
+ raise ParserFail.new("AtLeast: #{ex.message}")
+ end
+ end
+end
+