在scala中,如何使用模式匹配来匹配具有指定长度的列表?

Han*_*Sun 2 functional-programming scala list pattern-matching

我的代码如下所示:

1::2::Nil match {
  case 1::ts::Nil => "Starts with 1. More than one element"
  case 1::Nil => "Starts with 1. Only one element"
}
Run Code Online (Sandbox Code Playgroud)

我试图用来1::ts::Nil匹配以#开头1且长度大于1 的List .它适用于2元素列表,但是,这种模式不起作用3-element list,例如:

1::2::3::Nil match {
  case 1::ts::Nil => "Starts with 1. More than one element"
  case 1::Nil => "Starts with 1. Only one element"
}
Run Code Online (Sandbox Code Playgroud)

这不会有用.有人对此有想法吗?

小智 6

你不必在Nil上匹配.你可以做的是与其他人匹配.

1::Nil match {
   case 1::ts::rest => "Starts with 1. More than one element"
   case 1::Nil => "Starts with 1. Only one element"
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,其余部分不是List或Nil,并且您确保该元素具有多个元素,并且匹配ts然后休息

  • 改进:`{case 1 :: Nil => 1; case 1 :: rest => 2}`. (5认同)