3 ms·
But how to implement laziness?
by amelius 11y ago
But how to implement laziness?
- homarp 11y agodon't do it yet.
- tel 11y agoNon-strictness can be implemented with functions. function thunk(f) { return { force: f } } This, for instance, gives you a lazy stream function unfold(step, state) { return thunk(function () { let m = step(state); if (!m.ok) { return {}; } else { return { head: m.value, tail: unfold(step, m.state) }; } }); }
- hawkice 11y agoSo, thunks should avoid multiple evaluation, too, and handle exceptions in a way that is relatively coherent. I like: function thunk(f) { var evaluated = false; var value = undefined; var excepting = undefined; return { force: function () { if (!evaluated) { evaluated = true; try { value = f(); } catch (e) { excepting = e; } } if (excepting) throw excepting; return value; }} }