chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

Add an IterParser::fold method

Open Philogy opened this issue 2 months ago • 3 comments

It seems the only way I can really "collect" the values from a repeated / separated_by combinator is via .collect? My issue with is that basically requires a heap allocation by using Vec or some alternative data structure that implements Collect. Other patterns I would intuitively expect to work such as .fold do not seem to work for some reason?

// ... more code
                choice((
                    ident.clone().map(ParamExpr::NameRef),
                    label.clone().map(ParamExpr::FuncRef),
                    data_ref.clone().map(ParamExpr::DataRef),
                    u256_value.clone().map(|v| ParamExpr::Num(arena.alloc(v))),
                ))
                .repeated()
// Can't do ?
                .fold(BVec::with_capacity_in(16, arena), |mut exprs, expr| {
                    exprs.push(expr);
                    exprs
                }),

The error message Rust gives me for why .fold isn't working is very unreadable. Any ideas?

Image

Philogy avatar Oct 08 '25 20:10 Philogy

Nevermind, figured it out, you can work around using foldl, I thought I wasn't able to get that to work but you can just:

            empty().map(|_| BVec::with_capacity_in(DEFAULT_STMT_PARAMS_CAPACITY, arena)).foldl(
                choice((
                    ident.clone().map(ParamExpr::NameRef),
                    label.clone().map(ParamExpr::FuncRef),
                    data_ref.clone().map(ParamExpr::DataRef),
                    u256_value.clone().map(|v| ParamExpr::Num(arena.alloc(v))),
                ))
                .repeated(),
                |mut exprs, expr| {
                    exprs.push(expr);
                    exprs
                },
            );

Philogy avatar Oct 08 '25 21:10 Philogy

It might be worth implementing a dedicated fold that has this behaviour though... Mind if I change the issue title and reopen?

zesterer avatar Oct 12 '25 15:10 zesterer

Yeah of course, feel free to reopen! @zesterer

Philogy avatar Oct 12 '25 16:10 Philogy