Last active
March 22, 2018 13:43
-
-
Save lincore81/ab6c1e6c43962a798191fc764923b4b2 to your computer and use it in GitHub Desktop.
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
| const otherwise = true; | |
| const isNumber = n => typeof n === 'number'; | |
| const eq = a => b => a === b; | |
| const fib = match([ | |
| eq(0), 1, | |
| eq(1), 1, | |
| x < 0, 0, | |
| isNumber, () => fib(x-1) + fib(x-2), | |
| otherwise, () => {throw new Error('Not a number');} | |
| ]); | |
| function match(conds) { | |
| return (x) => { | |
| if (conds.length % 2) throw new Error('array must have an even length.'); | |
| for (let i = 0; i < conds.length; i+=2) { | |
| const cond = conds[i]; | |
| let pass = eval(cond, x); | |
| if (!pass) continue; | |
| return eval(conds[i+1], pass); | |
| } | |
| throw new Error(`Unmatched value: ${x}`); | |
| } | |
| function eval(expr, arg) { | |
| if (typeof expr === 'function') { | |
| return expr(arg) | |
| } | |
| return expr; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment