From 391bba24c5b373b3a4792d707834aaa72046f34f Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Tue, 6 Dec 2022 18:19:42 +0100 Subject: [PATCH] Use enumerate combinator --- 2022/src/common.rs | 12 ++++++++++++ 2022/src/day05.rs | 11 ++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/2022/src/common.rs b/2022/src/common.rs index 674d56f..5ec5bc8 100644 --- a/2022/src/common.rs +++ b/2022/src/common.rs @@ -1,6 +1,7 @@ //! Common helper utilities to all days use anyhow::Result; +use nom::combinator::map; use nom::error::ErrorKind; use nom::error::ParseError; use nom::Finish; @@ -93,6 +94,17 @@ where } } +/// Add an index to repeated successful invocations of the embedded parser. +pub fn enumerate(f: impl Parser) -> impl FnMut(I) -> IResult { + let mut index = 0usize; + + map(f, move |v| { + let res = (index, v); + index += 1; + res + }) +} + /// Return the minimum and maximum of two unordered variables pub fn minmax(a: T, b: T) -> (T, T) where diff --git a/2022/src/day05.rs b/2022/src/day05.rs index 83960cc..e5c17fb 100644 --- a/2022/src/day05.rs +++ b/2022/src/day05.rs @@ -16,17 +16,16 @@ use nom::sequence::terminated; use nom::sequence::tuple; use nom::IResult; +use crate::common::enumerate; use crate::common::parse_input; type Move = (usize, usize, usize); type OwnedStacks = Vec>; fn parse_row<'a>(input: &'a [u8], stacks: &mut OwnedStacks) -> IResult<&'a [u8], ()> { - let mut index = 0usize; - // Forgive me for this crime fold_many1( - terminated( + enumerate(terminated( alt(( // Parse a delimited value into a Some(content) map(delimited(tag("["), take(1usize), tag("]")), |v: &[u8]| { @@ -36,9 +35,9 @@ fn parse_row<'a>(input: &'a [u8], stacks: &mut OwnedStacks) -> IResult<&'a [u8], map(tag(" "), |_| None), )), opt(tag(" ")), - ), + )), || (), - move |_, c| { + move |_, (index, c)| { if let Some(b) = c { if stacks.len() <= index { stacks.resize_with(index + 1, Vec::new); @@ -46,8 +45,6 @@ fn parse_row<'a>(input: &'a [u8], stacks: &mut OwnedStacks) -> IResult<&'a [u8], stacks[index].push(b) } - - index += 1; }, )(input) }