pub fn fold<I, E, F, G, H, J, R>(
range: J,
parser: F,
init: H,
fold: G,
) -> impl Parser<I, Output = R, Error = E>
Expand description
Applies a parser and accumulates the results using a given function and initial value. Fails if the amount of time the embedded parser is run is not within the specified range.
ยงArguments
range
Constrains the number of iterations.- A range without an upper bound
a..
allows the parser to run until it fails. - A single
usize
value is equivalent tovalue..=value
. - An empty range is invalid.
- A range without an upper bound
parse
The parser to apply.init
A function returning the initial value.fold
The function that combines a result off
with the current accumulator.
use nom::multi::fold;
use nom::bytes::complete::tag;
fn parser(s: &str) -> IResult<&str, Vec<&str>> {
fold(
0..=2,
tag("abc"),
Vec::new,
|mut acc: Vec<_>, item| {
acc.push(item);
acc
}
).parse(s)
}
assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
assert_eq!(parser("123123"), Ok(("123123", vec![])));
assert_eq!(parser(""), Ok(("", vec![])));
assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));