Skip to content

Instantly share code, notes, and snippets.

@christiantakle
Last active December 10, 2015 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiantakle/b291586c6c9dbe393bf8 to your computer and use it in GitHub Desktop.
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.
// 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