Skip to content

Instantly share code, notes, and snippets.

@eoncarlyle
Created December 26, 2024 19:53
Show Gist options
  • Select an option

  • Save eoncarlyle/309b7da602df8ea6d4ab7a01fc83bcbb to your computer and use it in GitHub Desktop.

Select an option

Save eoncarlyle/309b7da602df8ea6d4ab7a01fc83bcbb to your computer and use it in GitHub Desktop.
Incorrect Monad Explanation
import { pipe } from "fp-ts/function";
import { IO, chain as chainIO, map as mapIO } from "fp-ts/IO";
const effect: IO<string> = () => "myString";
// Functors implement map, and these are useful
const singleChange: (fa: IO<string>) => IO<string> = mapIO((input: string) =>
input.toUpperCase(),
);
const singleChangeApplied = singleChange(effect);
//However, because they do not accept a monad as an input, they are limited
//That is where chain (usually refered to as map comes in)
const chainedChanges = chainIO((input: string) => () => input.repeat(2))(
chainIO((input: string) => () => input.toUpperCase())(effect),
);
//Not only does `chainedChanges` look ugly as hell, it doesn't actually do anything.
//Let's use OCaml style pipes to make this clearer
const prettierChained = pipe(
effect,
chainIO((input: string) => () => input.toUpperCase()),
chainIO((input: string) => () => input.repeat(2)),
chainIO((input: string) => () => console.log(input)),
);
//"MYSTRINGMYSTRING"
prettierChained();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment