Skip to content

Instantly share code, notes, and snippets.

@r17x
Created May 16, 2022 15:38
Show Gist options
  • Save r17x/2c62c1b8a1cf843406d8924caa7afa7c to your computer and use it in GitHub Desktop.
Save r17x/2c62c1b8a1cf843406d8924caa7afa7c to your computer and use it in GitHub Desktop.
// we write Maybe module (stolen from haskell)
module Maybe = {
type t<'a> =
| Just('a)
| Nothing
let fmap = (x, fn) =>
switch x {
| Just(x) => Just(x->fn)
| Nothing => Nothing
}
let apply = (x, fn) =>
switch x {
| Nothing => Nothing
| Just(x) =>
switch fn {
| Nothing => Nothing
| Just(fn) => Just(x->fn)
}
}
let bind = (x, fn) =>
switch x {
| Just(x) => x->fn
| Nothing => Nothing
}
}
let functor = Maybe.fmap(Just(5), x => x + 5) // Just(10)
let applicative = Maybe.apply(Just(2), Just(x => x + 3)) // Just(5)
let bind = Maybe.bind(Just(6), x => Just(x + 3)) // Just(9)
@r17x
Copy link
Author

r17x commented May 16, 2024

let apply = (x, fn) =>
    switch (x, fn) {
      | (Nothing, _) 
      | (_, Nothing) => Nothing
      | (Just(x), Just(fn)) => Just(x->fn)
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment