▲ | LegionMammal978 5 days ago | ||||||||||||||||
Sometimes the messy translation into an explicit stack and dispatch loop is necessary, if you want to pause the calculation, serialize the current state, and reconstitute it later. (E.g., if you want to add disk-saved checkpoints, a frequent hassle in some of my projects.) Coroutines can get you the equivalent of pausing and resuming for a recursive routine, but I'm not aware of any language that lets you serialize the call stack. | |||||||||||||||||
▲ | Jtsummers 5 days ago | parent | next [-] | ||||||||||||||||
> I'm not aware of any language that lets you serialize a whole call stack. That's basically what continuations provide. Scheme, SML, and others provide them. | |||||||||||||||||
| |||||||||||||||||
▲ | tylerhou 5 days ago | parent | prev | next [-] | ||||||||||||||||
It is much easier and more maintainable to convert to continuation passing style. If you also use defunctionalization to allocate closures on a stack instead of a fresh heap allocation for every closure, you will achieve performance on par with an explicit stack. (In fact, defunctionalization is a mechanical transformation the produces exactly the data you would store in an explicit stack!) Before I knew about CPS and defunctionalization, I wrote a Python decorator that did exactly the transformation you describe. https://github.com/tylerhou/fiber. Now I know about CPS and defunctionalization, I realize that my work was not the best implementation (but it was a fun learning experience!). | |||||||||||||||||
| |||||||||||||||||
▲ | themk 5 days ago | parent | prev [-] | ||||||||||||||||
There is a library for Haskell that will do it. Though it doesn't support all GHC versions. It's very nifty if you need it. |