aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-11 22:33:18 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-11 22:33:18 +1300
commit06d18bc4df24b65df5e54eb3ee9e243ed35cb271 (patch)
tree780b59a92c1087d05854564bfe7f9b8ee9c7dc66 /src
parent449f03b6078effac65ce90e71edb89108ad36436 (diff)
Documentation for Map
Diffstat (limited to 'src')
-rw-r--r--src/parcom.cr13
-rw-r--r--src/parcom/map.cr30
2 files changed, 30 insertions, 13 deletions
diff --git a/src/parcom.cr b/src/parcom.cr
index 44a770c..aa7abba 100644
--- a/src/parcom.cr
+++ b/src/parcom.cr
@@ -81,19 +81,6 @@ module Parcom
end
end
- class Map(T, V, U) < Parser(T, U)
- def initialize(@p : Parser(T, V), &block : V -> U)
- @f = block
- end
-
- def parse(tokens : Tokens(T)) : Result(T, U)
- result = @p.parse(tokens)
- Result.new(result.tokens, @f.call(result.value))
- rescue ex : ParserFail
- raise ParserFail.new("Map: #{ex.message}")
- end
- end
-
class Phrase(T, V)
@p : Map(T, {V, Nil}, V)
diff --git a/src/parcom/map.cr b/src/parcom/map.cr
new file mode 100644
index 0000000..34961b5
--- /dev/null
+++ b/src/parcom/map.cr
@@ -0,0 +1,30 @@
+require "./parser.cr"
+
+module Parcom
+ # `Map` is a `Parser` that tries to parse using another parser,
+ # and then changing the result of that parser to a different value.
+ #
+ # Example:
+ # ```
+ # # Where `Digits` is some parser that returns an array of digit characters
+ # parse_i32 = Digits.new.map { |x| x.join.to_i32 }
+ # result = parse_i32.parse(Tokens.from_string("1234"))
+ # result.value # => 1234 (Int32)
+ # ```
+ class Map(T, V, U) < Parser(T, U)
+ # Accepts the parser to use and the function to apply to the result.
+ def initialize(@p : Parser(T, V), &block : V -> U)
+ @f = block
+ end
+
+ # Tries to parse with the given parser and applies the
+ # function to the result if successful.
+ def parse(tokens : Tokens(T)) : Result(T, U)
+ result = @p.parse(tokens)
+ Result.new(result.tokens, @f.call(result.value))
+ rescue ex : ParserFail
+ raise ParserFail.new("Map: #{ex.message}")
+ end
+ end
+end
+