3 ms·
Non-strictness can be implemented with functions. function thunk(f) { return { force: f } } This, for instance, gives you a lazy stream function unfo
by tel 11y ago
Non-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; }} }