带连词的模式匹配(PatternA AND PatternB) [英] Pattern matching with conjunctions (PatternA AND PatternB)
问题描述
Scala 有一个语言特性来支持模式匹配中的析取('Pattern Alternatives'):
Scala has a language feature to support disjunctions in pattern matching ('Pattern Alternatives'):
x match {
case _: String | _: Int =>
case _ =>
}
但是,如果审查满足 PatternA 和 PatternB(连词),我经常需要触发一个动作.
However, I often need to trigger an action if the scrutiny satisfies PatternA and PatternB (conjunction.)
我创建了一个模式组合器&&"这增加了这种能力.三句话让我想起我为什么喜欢 Scala!
I created a pattern combinator '&&' that adds this capability. Three little lines that remind me why I love Scala!
// 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 _ => "_"
}
讨论要点
- 有没有现有的方法可以做到这一点?
- 这种方法有问题吗?
- 这种方法能否创建任何其他有用的组合器?(例如,
Not
) - 是否应该将这样的组合器添加到标准库中?
更新我刚刚被问到编译器如何解释 case A &&住宿加早餐旅馆C
.这些是中缀运算符模式(Scala 参考的第 8.1.9 节).您也可以使用标准提取模式 (8.1.7) 将其表示为 &&(&&(A, B), C).'请注意表达式是如何从左到右关联的,按照正常的中缀运算符方法调用,如
Boolean#&&in
val b = true &&假&&真的`.
UPDATE
I've just been asked how the compiler interprets case A && B && C
. These are infix operator patterns (Section 8.1.9 of the Scala Reference). You could also express this with standard extract patterns (8.1.7) as &&(&&(A, B), C).' Notice how the expressions are associated left to right, as per normal infix operator method calls like
Boolean#&&in
val b = true && false && true`.
推荐答案
我真的很喜欢这个技巧.我不知道有任何现有的方法可以做到这一点,而且我不认为它有任何问题——不过,这并不意味着什么.我想不出任何方法来创建 Not
.
I really like this trick. I do not know of any existing way to do this, and I don't foresee any problem with it -- which doesn't mean much, though. I can't think of any way to create a Not
.
至于将其添加到标准库...也许吧.但是我觉得有点难.另一方面,如何让 Scalaz 人加入它?它看起来更像是他们自己的辖区.
As for adding it to the standard library... perhaps. But I think it's a bit hard. On the other hand, how about talking Scalaz people into including it? It looks much more like their own bailiwick.
这篇关于带连词的模式匹配(PatternA AND PatternB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!