Last active
January 1, 2018 12:24
-
-
Save dwickstrom/3f2e630e29b07d7f342c0ff420ce341c to your computer and use it in GitHub Desktop.
JS pattern matching
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
// fooIsBar :: Int -> String | |
const fooIsBar = x => | |
x == 1 ? 'one' | |
: x == 2 ? 'two' | |
: x == 3 ? 'three' | |
: x == 4 ? 'four' | |
: /* or */ 'too much' | |
// sign :: Int -> Int | |
const sign = x => | |
x > 0 ? 1 | |
: x === 0 ? 0 | |
: x < 0 ? -1 | |
: /* else */ throw new TypeError('Not an integer') | |
// take :: Int -> [a] -> [a] | |
const take = n => xs => | |
xs.length === 0 ? [] | |
: n === 0 ? [] | |
: /* otherwise */ [head (xs), ...take (n-1) | |
(tail(xs))] | |
// factorial :: Int -> Int | |
const factorial = n => | |
n === undefined ? 0 | |
: n === 0 ? 1 | |
: /* otherwise */ n * factorial (n -1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment