Welcome to (thunk) town
I have always wanted to have a place online that I can write some of my ideas to, but never got around to doing it. Much like a thunk actually, so it’s fitting that this first piece maybe explains what that is (and that this domain was available for a reasonable price).
What is a Thunk?
For those amongst you who were too lazy to click on the above link and read a bit about it on Wikipedia, here is the gist of it:
A thunk is a subroutine used to inject a calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed.
They have applications in compilers and functional programming, mainly for those
interested in call-by-name evaluation. For the normal person, its basically
an anonymous/lambda function, but here is the classic illustrative example, the
custom if statement:
const myIf = (condition, then, otherwise) =>
(condition ? then : otherwise);
using this in a function immediately falls over:
const factorial = (n) =>
myIf(n === 0, 1, n * factorial(n - 1));
factorial(3); // RangeError: Maximum call stack size exceeded
JavaScript (🤮) eagerly evaluates every argument, meaning it tries to
calculate factorial(-1), factorial(-2), … forever. The builtin ternary
operator doesn’t do this and works normally. Luckily, it is possible to learn
this power:
const myIf = (condition, then, otherwise) =>
(condition ? then() : otherwise());
those two silly looking then() and otherwise() statements? Thunks!
// finally, some factorials (ignore the weird '() => 1' construct)
const factorial = (n) =>
myIf(n === 0, () => 1, () => n * factorial(n - 1));
What else is a Thunk?
For the worldly readers, you have probably thought of the phrase “Who woulda thunk it?” at least once while reading this, and yes, as the Wikipedia article confirms, this is the exact same thing:
The term originated as a whimsical irregular form of the verb think. It refers to the original use of thunks in ALGOL 60 compilers, which required special analysis (thought) to determine what type of routine to generate.
No promises that I ever write another thing, but welcome to town!