Proposal for lambdas and closures

Here’s a

and here’s a direct link to the

We’ve had a ton of discussion of this over the years, so I’m following the process and creating a PR with a completed design document.

It’s intended as a draft and comments are more than welcome. I’m trying to follow the process outlined in the readme on design-docs. This is me following step one:

Write a design document roughly following the template. Designs that do not present convincing motivation, demonstrate understanding of the impact of the design, or are disingenuous about the drawbacks or alternatives tend to be poorly received. Share it with the Stan core developers, advertising it on discourse and ideally the weekly meeting.

The next step is this:

Anyone involved may schedule meetings to discuss the design with interested parties over a video chat. It’s generally a good idea to get an approving stakeholder involved for at least one of these. A design may be postponed if we don’t want to evaluate the proposal immediately for reasons such as not being urgent or depending on other designs to be completed.

I’m happy to schedule meetings to discuss the proposal.

I’m particularly keen to get feedback from @Matthijs on this, particularly on whether we should impose covariance and contravariance on function and container types.


Hey Bob,

Thanks again for the excellent write-up. I submitted a review for your closures proposal - in my opinion the only thing that’s missing is a discussion of closures by reference vs. by value, and then choosing one of those in the proposal. Matthijs mentioned he’d take a look soon too as I know he has some thoughts on this.


I suggested we use the equivalent of C++'s [&], which implicitly captures all variables by reference.

Would there be a reason for calling by value (copying)?

Also, I’m not sure how to write up closures much more formally. This is relying pretty heavily on understanding what’ll happen by just compiling to C++. This has gotten us into trouble before.

I think the big issue to deal with is dangling reference errors and what to do with GPU/MPI calls that want data distinctions and with map_rect and integrate_ode and presumably the algebraic solver, too.

Ah, okay. Should we continue the discussion on the PR? There are some more comments and context there.

OK. I’m waiting for everyone to get back before taking this up again, so no rush.

One consideration - Matthijs, Michael, Maria, and other language folks are remote so if there’s a version of this that can happen in an online venue that’d be nice. Otherwise happy to talk in person or maybe in a hangout the week of the 26th.