Skip to content

Instantly share code, notes, and snippets.

@mads-hartmann
Created January 23, 2011 09:45
Show Gist options
  • Save mads-hartmann/791943 to your computer and use it in GitHub Desktop.
Save mads-hartmann/791943 to your computer and use it in GitHub Desktop.
Pattern matching as a control structure
/*
I want to use pattern matching in coffeescript as a more capable switch. It uses destructuring
assignments to figure out which of the cases that matches. So it can match on the entire
structure of the object instead of just an integer.
(* in F# *)
let list = [1;2;3;4]
match list with
| [] -> printfn "empty list"
| x :: xs -> printfn "first element is " + x
*/
// in Scala
val list = 1 :: 2 :: 3 :: 4 :: Nil
list match {
case Nil => println("empty list")
case x :: xs => println("first element is " + x)
}
@TrevorBurnham
Copy link

I'm afraid you're stuck using if/then or switch/when, though if you have a detailed proposal for how to translate Scala's pattern-matching into JavaScript, you should definitely propose it.

Here's an equivalent of your example in CoffeeScript:

list = [1, 2, 3, 4]
if list.length is 0
  console.log 'Empty list'
else
  x = list[0]
  xs = list[1..]
  console.log "First element is #{x}"

You could, of course, write a function to split the list into a head and a tail:

headTail = (list) -> [list[0], list[1..]]
[x, xs] = headTail list

Be sure to take a look at Underscore.js and its Underscore.coffee implementation.

@mads-hartmann
Copy link
Author

Hey Trevor,

Thanks for replying. I will take a look at it to see if it's possible to translate Scala's pattern-matching into javascript. I'm about to start my bachelor project where I will write a collections library for javascript in Coffeescript and pattern matching (scala style) would really help there.

Thanks,
Mads

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment