scala的pattern match的两个问题——正则表达式和List


scala exercise 上做练习,在pattern match那一章的时候遇到两个题不理解,请大家帮我看下吧。

  1. 处理正则表达式

 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将参数的值放在字符串中的相应位置。

  1. 处理List

 val r = List(1, 2, 3) match {
  case x :: y :: Nil => y
  case _ => 0
}

r should be(0)

这个对 Nil 的理解不够,没想出怎么解释

scala 正则表达式 list

大葱小黄瓜君 10 years, 1 month ago
  1. 正则表达式用在 pattern match 时会去匹配这个整个串,同时把group的东西提取出来
  2. 首先,双冒号表示List的拼接。然后,x::y::Nil 中冒号是右结合,所以实际运行的过程是x::(y,Nil),然后再到(x,y,Nil),这个实际上就是(x,y)。而两个元素的List跟三个元素的List匹配不上,所以到下一个匹配,即r=0
small妖 answered 10 years, 1 month ago

Your Answer