Last active
March 17, 2021 06:03
-
-
Save yiminghe/83d840c63c6903c08ae0da0456ef297b to your computer and use it in GitHub Desktop.
haskell applicative function in js
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
function callFn(f, ...args) { | |
if (f.length === 0) { | |
return f(); | |
} | |
if (f.length === args.length) { | |
return f(...args); | |
} | |
if (f.length > args.length) { | |
const ret = f.bind(null, ...args); | |
ret.fn_name = `(${f.fn_name}(bind))`; | |
return ret; | |
} | |
// TODO < | |
throw new Error('TODO') | |
} | |
function applicativeFn(f, g) { | |
const ret = (x) => { | |
return callFn(callFn(f, x), callFn(g, x)); | |
}; | |
ret.fn_name = `(${f.fn_name} + ${g.fn_name})`; | |
return ret; | |
} | |
const pure = (f) => { | |
const ret = () => f; | |
ret.fn_name = `${f.fn_name}(pure)`; | |
return ret; | |
}; | |
const plusFn = (a, b) => a + b; | |
plusFn.fn_name = 'plusFn'; | |
const plus3 = (a) => a + 3; | |
plus3.fn_name = 'plus3'; | |
const mul100 = (a) => a * 100; | |
mul100.fn_name = 'mul100'; | |
// (+) <$> (+3) <*> (*100) $ 5 | |
const fn = applicativeFn(applicativeFn(pure(plusFn), plus3), mul100); | |
console.log(fn(5)); | |
// (+) <*> (+3) $ 2 | |
const fn3 = applicativeFn(plusFn, plus3); | |
console.log(fn3(2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment