Skip to content

Instantly share code, notes, and snippets.

@kamoshi
Created September 4, 2023 18:25
Show Gist options
  • Save kamoshi/93f19e7d81ec0225ed5b9b0b28e78d74 to your computer and use it in GitHub Desktop.
Save kamoshi/93f19e7d81ec0225ed5b9b0b28e78d74 to your computer and use it in GitHub Desktop.
Applicative Maybe example in JavaScript
const Nothing = { kind: "Nothing" };
const Just = (val) => ({ kind: "Just", val: () => val });
function pure(val) {
return Just(val);
}
function fmap(f, x) {
return (x.kind == "Nothing")
? Nothing
: Just(f(x.val()))
}
function ap(f) {
return (f.kind == "Nothing")
? (_) => Nothing
: (x) => fmap(f.val(), x);
}
function main(){
const effectA = Just(10);
const effectB = Just(30);
const effectC = Just(33);
const effectD = Just(33);
const collect = (a) => (b) => (c) => (d) => [a, b, c, d];
const f = pure(collect);
const res1 = ap (f) (effectA);
const res2 = ap (res1) (effectB);
const res3 = ap (res2) (effectC);
const res4 = ap (res3) (effectD);
console.log(res4.val());
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment