This commit is contained in:
Greg Shuflin 2024-01-26 09:22:19 -08:00
parent bffaca4d68
commit f2ff509748
2 changed files with 23 additions and 0 deletions

View File

@ -16,3 +16,13 @@ where
Ok((results, acc))
}
}
pub fn optional<I, O, E>(parser: impl Parser<I, O, E>) -> impl Parser<I, Option<O>, E>
where
I: Clone,
{
move |input: I| match parser.parse(input.clone()) {
Ok((output, rest)) => Ok((Some(output), rest)),
Err(_e) => Ok((None, input)),
}
}

View File

@ -74,4 +74,17 @@ mod tests {
let output = parser.parse("aaaaaaaabcd").unwrap();
assert_eq! {((10, 'b'), "cd"), output};
}
#[test]
fn test_optional() {
let parser = sequence(
optional(literal("alpha")),
sequence(repeated(literal(" ")), literal("beta")),
);
let output1 = parser.parse(" beta").unwrap();
assert_eq!(output1.0 .0, None);
let output2 = parser.parse("alpha beta").unwrap();
assert_eq!(output2.0 .0, Some("alpha"));
}
}