Created
December 26, 2024 19:53
-
-
Save eoncarlyle/309b7da602df8ea6d4ab7a01fc83bcbb to your computer and use it in GitHub Desktop.
Incorrect Monad Explanation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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