Created
April 16, 2011 00:35
-
-
Save sdiehl/922704 to your computer and use it in GitHub Desktop.
Pattern Matching in Coffeescript
This file contains 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
# Haskell style pattern matching using: | |
# https://github.com/jfd/match-js/blob/master/match.js | |
{Match, incl } = require './match.js' | |
_ = Match.incl | |
print = console.log | |
fib = Match( | |
0, -> 0 | |
1, -> 1 | |
Number, (n) -> fib(n-1)+fib(n-2) | |
) | |
head = Match( | |
Array, ([x,xs...]) -> x | |
) | |
tail = Match( | |
Array, ([x,xs...]) -> xs | |
) | |
elem = Match( | |
[Number, []], (n) -> false | |
[Number, Array] , (n, [x,xs...]) -> x == n or elem([n,xs]) | |
) | |
print fib 6 | |
print head [1,2,3] | |
print tail [1,2,3] | |
print elem [1,[1,2,3]] | |
print elem [4,[1,2,3]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment