ret*_*nym 60 scala pattern-matching
Scala具有支持模式匹配中的析取的语言功能('Pattern Alternatives'):
x match {
case _: String | _: Int =>
case _ =>
}
Run Code Online (Sandbox Code Playgroud)
但是,如果仔细检查满足PatternA 和 PatternB(连接),我经常需要触发一个动作.
我创建了一个模式组合器'&&',它增加了这个功能.三条小线条让我想起为什么我爱斯卡拉!
// Splitter to apply two pattern matches on the same scrutiny.
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 _ => "_"
}
Run Code Online (Sandbox Code Playgroud)
Not)更新
我刚刚被问到编译器如何解释case A && B && C.这些是中缀运算符模式(Scala参考的第8.1.9节).您也可以使用标准提取模式(8.1.7)将其表示为&&(&&(A, B), C).' Notice how the expressions are associated left to right, as per normal infix operator method calls like布尔#&& inval b = true && false && true`.
Dan*_*ral 13
我真的很喜欢这个技巧.我不知道有任何现有的方法可以做到这一点,我也没有预见到它的任何问题 - 但这并不意味着什么.我想不出有什么方法可以创造一个Not.
至于将它添加到标准库......也许吧.但我认为这有点难.另一方面,如何与Scalaz人交谈包括它?它看起来更像是他们自己的bailiwick.
| 归档时间: |
|
| 查看次数: |
6763 次 |
| 最近记录: |