Created
June 23, 2010 11:11
-
-
Save teigen/449789 to your computer and use it in GitHub Desktop.
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
// 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. |
@retronym thanks for the links.. Love that hand rolled matcher!
Does anyone know why @ is part of the patternmatching syntax, when it can be implemented as a library so easily ?
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
See also:
"Pattern Matching with Conjunctions": http://stackoverflow.com/questions/2261358/pattern-matching-with-conjunctions-patterna-and-patternb
"Hand rolled pattern matcher": http://gist.github.com/376773