chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

Parsing a(ba)* in 1.0.0-alpha.4

Open 01mf02 opened this issue 11 months ago • 5 comments

I am converting a parser from chumsky 0.9 to 1.0.0-alpha.4. During this, I noticed a pattern that I found quite nontrivial to translate. In particular, a parser for a(ba)*, where a and b are parsers that have the same output type T, and we want to obtain all parsed elements as Vec<T>. (It's like separated_by, but keeping the separators.) In chumsky 0.9, this looked something like:

a.chain(b.chain(a).repeated().flatten()).collect()

In the new chumsky, however, there is no more chain. After some struggling, I came up with the following equivalent in chumsky 1.0.0-alpha.4:

let head = a.map(|x| Vec::from([x]));
head.foldl(b.then(a).repeated(), |mut acc, (x, y)| {
    acc.push(x);
    acc.push(y);
    acc
})

This is significantly longer, and IMHO, much harder to understand. (My actual example even involves nested foldl Is there some more canonical way to do this?

01mf02 avatar Jul 14 '23 08:07 01mf02