Created
February 15, 2025 00:56
-
-
Save codegod100/a50dca8bbeb85ebbd44e7af7380b8e52 to your computer and use it in GitHub Desktop.
monad
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
| // Define the Monad structure using `unit` and `bind` | |
| type Monad<M extends { __type: any }> = { | |
| unit: <A>(value: A) => M & { __type: A }; | |
| bind: <A, B>(ma: M & { __type: A }, f: (a: A) => M & { __type: B }) => M & { __type: B }; | |
| }; | |
| // Example: Maybe monad implementation | |
| type Just<A> = { __type: A; tag: 'Just'; value: A }; | |
| type Nothing = { __type: any; tag: 'Nothing' }; | |
| type Maybe<A> = Just<A> | Nothing; | |
| const Maybe = { | |
| unit: <A>(value: A): Maybe<A> => ({ __type: value as A, tag: 'Just', value }), | |
| nothing: { __type: undefined, tag: 'Nothing' } as Nothing, | |
| }; | |
| const MaybeMonad: Monad<Maybe<any>> = { | |
| unit: <A>(value: A) => Maybe.unit(value), | |
| bind: <A, B>(ma: Maybe<A>, f: (a: A) => Maybe<B>) => | |
| ma.tag === 'Just' ? f(ma.value) : Maybe.nothing, | |
| }; | |
| // Usage: | |
| const result = MaybeMonad.bind( | |
| MaybeMonad.unit(2), | |
| (n: number) => MaybeMonad.unit(n * 3) // Returns Just(6) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment