Created
February 14, 2010 14:19
-
-
Save retronym/304046 to your computer and use it in GitHub Desktop.
A combinator to allow pattern conjunctions
This file contains hidden or 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
| // Splitter to apply two pattern matches on the same scrutinee. | |
| case object && { | |
| def unapply[A](a: A) = Some((a, a)) | |
| } | |
| // Extractor object matching first character. | |
| object StartsWith { | |
| def unapply(s: String) = s.headOption | |
| } | |
| // Extractor object matching last character. | |
| object EndsWith { | |
| def unapply(s: String) = s.reverse.headOption | |
| } | |
| // Extractor object matching length. | |
| object Length { | |
| def unapply(s: String) = Some(s.length) | |
| } | |
| "foo" match { | |
| case StartsWith('f') && EndsWith('f') => "f.*f" | |
| case StartsWith('f') && EndsWith(e) && Length(3) if "aeiou".contains(e) => "f..[aeiou]" | |
| case _ => "_" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment