Effect finally clicked
For a couple of years now I have danced in and out of understanding Effect-TS. While working on larger codebases with remote teams, it was always in the backseat and just something I wanted to learn to pique my own curiosity in this idea they brought to Typescript, that of writing “blueprints” for your program by effectively hiding everything behind thunks. Effect then uses a fiber-based concurrency system to execute Effectful programs in what turns out to be quite a graceful manner.
How I finally got it
One you realize everything is just thunkified, and what hiding every computation behind an anonymous function entails, it’s quite simple.
A thunk type in TS is just:
type Thunk<A> = () => A;
So the simplest of examples looks like:
// Instead of this
const thing: number = 5;
// wrap it in a thunk
const thunked: () => number = () => 5;
A practical way to describe the difference between these two computations is as follows:
// This logs the same number 3 times
const randomNumber: number = Math.random();
console.log(randomNumber);
console.log(randomNumber);
console.log(randomNumber);
// This logs 3 different numbers
const randomNumberThunk: () => number = () => Math.random();
console.log(randomNumberThunk);
console.log(randomNumberThunk);
console.log(randomNumberThunk);
So, “trapping” the value of any given computation behind an anonymous function, is thereby delaying its execution until it’s explicitly called by a runtime.
This is the core concept that enabled me to understand Effect after several tries.
Over the next few days I will continue using this awesome workshop, specifically now the CLI and webserver sections, to practice translating programs into Effectful TS.