Last active
December 10, 2015 20:38
-
-
Save christiantakle/b291586c6c9dbe393bf8 to your computer and use it in GitHub Desktop.
Example of poormans pattern matching in Javascript. It useful in some cases. Beware of recursive definitions like this. It will blow the stack.
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
// Classic Javascript | |
function fib(n) { | |
if(n === 0) { return 0 } | |
if(n === 1) { return 1 } | |
return fib(n-1) + fib(n-2)} | |
// Non-auto-curry | |
const mkCases = // :: Object Functions -> a -> b | |
cases => key => | |
(cases[key]? cases[key] : cases["_"])(key) | |
const fib = // :: Number -> Number | |
mkCases({ | |
0: _ => 0, | |
1: _ => 1, | |
_: n => fib(n-1) + fib(n-2) | |
}) | |
/* | |
-- Haskell | |
fib 0 = 0 | |
fib 1 = 1 | |
fib n = fib (n-1) + fib (n-2) | |
fib n = | |
case n of | |
0 -> 0 | |
1 -> 1 | |
_ -> fib (n-1) + fib (n-2) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment