Skip to content

Instantly share code, notes, and snippets.

@sdiehl
Created April 16, 2011 00:35
Show Gist options
  • Save sdiehl/922704 to your computer and use it in GitHub Desktop.
Save sdiehl/922704 to your computer and use it in GitHub Desktop.
Pattern Matching in Coffeescript
# 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