scala的pattern match的两个问题——正则表达式和List
在 scala exercise 上做练习,在pattern match那一章的时候遇到两个题不理解,请大家帮我看下吧。
- 处理正则表达式
scala
val EatingRegularExpression = """Eating Alert: bear=([^,]+),\s+source=(.+)""".r //.r turns a String to a regular expression val SittingRegularExpression = """Sitting Alert: bear=([^,]+),\s+source=(.+)""".r val SleepingRegularExpression = """Sleeping Alert: bear=([^,]+),\s+source=(.+)""".r def goldilocks(expr: String) = expr match { case (EatingRegularExpression(bear, source)) => "%s said someone's been eating my %s".format(bear, source) case (SittingRegularExpression(bear, source)) => "%s said someone's been sitting on my %s".format(bear, source) case (SleepingRegularExpression(bear, source)) => "%s said someone's been sleeping in my %s".format(bear, source) case _ => "what?" } goldilocks("Eating Alert: bear=Papa, source=porridge") should be("Papa said someone's been eating my porridge") goldilocks("Sitting Alert: bear=Mama, source=chair") should be("Mama said someone's been sitting on my chair")
这个正则表达式的处理过程可不可以描述如下:
首先根据pattern match的部分匹配规则,知道应该选哪个case,然后将bear和source两个参数通过正则表达式过滤出来,然后根据format将参数的值放在字符串中的相应位置。
- 处理List
val r = List(1, 2, 3) match {
case x :: y :: Nil => y
case _ => 0
}
r should be(0)
这个对
Nil
的理解不够,没想出怎么解释
大葱小黄瓜君
10 years, 1 month ago