Skip to content

Instantly share code, notes, and snippets.

@teigen
Created June 23, 2010 11:11
Show Gist options
  • Save teigen/449789 to your computer and use it in GitHub Desktop.
Save teigen/449789 to your computer and use it in GitHub Desktop.
// scala @ syntax in patternmatching implemented as a library
object `@` {
def unapply[A](a:A) = Some(a, a)
}
// usage
val Nums = """(\d),(\d)""".r
"1,2" match {
case a `@` Nums(first, second `@` "2") => println(a + "-"+first + "-" + second)
}
// prints
1,2-1-2
// it's actually more general
"1,2" match {
case Nums(a, b) `@` Nums(c, d) => println(List(a,b,c,d))
}
//prints
List(1, 2, 1, 2)
// -----
"1,2" match {
case Nums(a, b) @ Nums(c, d) => println(List(a,b,c,d))
}
error: '=>' expected but '@' found.
@teigen
Copy link
Author

teigen commented Jun 23, 2010

@retronym thanks for the links.. Love that hand rolled matcher!

@teigen
Copy link
Author

teigen commented Jun 23, 2010

Does anyone know why @ is part of the patternmatching syntax, when it can be implemented as a library so easily ?

@retronym
Copy link

Actually case x => is syntactic sugar for case x @ _ =>. I showed Martin Odersky my &&[A, B] a couple weeks ago and he was a little surprised to see that this could be implemented as a library! So Scala can really suprise all of us, usually in good ways :)

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