Last active
August 29, 2015 14:22
-
-
Save AGhost-7/cbc1c523ac399c11072a to your computer and use it in GitHub Desktop.
Very basic Coffeescript pattern matching
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
class Message | |
class Greeting extends Message | |
class Shout extends Message | |
class Farewell extends Message | |
# Curry for reusing the match | |
match = (patterns...) -> (val) -> | |
for pat in patterns | |
if val instanceof pat[0] then return pat[1](val) | |
matcher = match( | |
[Greeting, -> console.log('hello!')] | |
[Shout, -> console.log('*SHOUTS*')] | |
[Message, (val) -> | |
for i in [1..5] | |
console.log('match not found for value ', val) | |
] | |
) | |
matcher(new Greeting) | |
matcher(new Shout) | |
matcher(new Farewell) | |
# >hello! | |
# >*SHOUTS* | |
# >match not found for value {} | |
# >match not found for value {} | |
# >match not found for value {} | |
# >match not found for value {} | |
# >match not found for value {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment