From 41829019b6ef6e1ea6c577e6b2b68c38237e2df7 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Fri, 26 Jan 2024 00:13:05 -0800 Subject: [PATCH] Map --- src/lib.rs | 12 ++++++++++++ src/map.rs | 13 +++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 src/map.rs diff --git a/src/lib.rs b/src/lib.rs index 245f314..35a9b8c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,11 @@ #![allow(dead_code)] //TODO eventually turn this off mod choice; +mod map; mod primitives; mod sequence; pub use choice::*; +pub use map::*; pub use primitives::*; pub use sequence::*; @@ -53,4 +55,14 @@ mod tests { let output = parser.parse("ara hajimete").unwrap(); assert_eq!(("ara", " hajimete"), output); } + + #[test] + fn test_map() { + let parser = map( + sequence(literal("a"), literal("b")), + |(_a, _b): (&str, &str)| 59, + ); + let output = parser.parse("abcd").unwrap(); + assert_eq!((59, "cd"), output); + } } diff --git a/src/map.rs b/src/map.rs new file mode 100644 index 0000000..7477308 --- /dev/null +++ b/src/map.rs @@ -0,0 +1,13 @@ +use crate::Parser; + +pub fn map(parser: P, map_fn: F) -> impl Parser +where + P: Parser, + F: Fn(O1) -> O2, +{ + move |input| { + parser + .parse(input) + .map(|(result, rest)| (map_fn(result), rest)) + } +}