在scala中,如何使用模式匹配来匹配指定长度的列表? [英] In scala, how can I use pattern match to match a list with specified length?

查看:105
本文介绍了在scala中,如何使用模式匹配来匹配指定长度的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示:

  1 :: 2 ::无匹配{
案例1 :: ts :: Nil => 以1开始不止一个元素
case 1 :: Nil => 开始于1.只有一个元素

我试着用 1 :: ts :: Nil 以匹配以 1 开头并且长度大于1的列表。它适用于2元素列表,但是,该模式不适用于 3元素列表,例如:

  1 :: 2 :: 3 :: Nil match {
case 1 :: ts :: Nil => 以1开始不止一个元素
case 1 :: Nil => 从1开始。只有一个元素

这不起作用。有人对此有何看法?

  1 ::无匹配{
case 1 :: ts :: rest => 以1开始不止一个元素
case 1 :: Nil => 从1开始。只有一个元素

一个列表或零,你确保该元素有超过1个元素与ts匹配,然后休息


My codes looks like this:

1::2::Nil match {
  case 1::ts::Nil => "Starts with 1. More than one element"
  case 1::Nil => "Starts with 1. Only one element"
}

I tried to use 1::ts::Nil to match the List who starts with 1 and whose length is greater than 1. It workes well for 2-element list, however, this pattern doesn't work for 3-element list, for example:

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"
}

This won't work..Does anyone have ideas about this?

解决方案

You don't have to match on Nil. What you could do instead is match on the rest.

1::Nil match {
   case 1::ts::rest => "Starts with 1. More than one element"
   case 1::Nil => "Starts with 1. Only one element"
}

With this code rest is than either a List or Nil and you make sure that the element has more than 1 element with the match on ts and then rest

这篇关于在scala中,如何使用模式匹配来匹配指定长度的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆