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)) + } +}