Scala匹配列表

时间:2016-03-04 19:37:23

标签: scala functional-programming

我正在尝试从List的{​​{1}}获取第一个和最后一个元素。以下是我现在正在尝试的内容:

Int

我在第def find(lista: List[Integer]) : (Int,Int) = { case (x) => (x,x) case (x1,x2) => (x2,x2) case hd :: _ :: tail => find(tail) } 行收到警告:

find(tail)

2 个答案:

答案 0 :(得分:2)

在这里你匹配一个元组:

case (x1,x2) => (x2,x2)

如果你想玩递归和模式匹配,你可以像:

object HeadTail{
  def find(lista: List[Int]) : (Int,Int) = {
    @tailrec
    def getLast(l: List[Int]): Int = l match {
      case h :: Nil => h
      case h :: tail => getLast(tail)
    }

    lista match {
      case Nil => throw new IllegalArgumentException("empty list")
      case h :: tail => (h, getLast(lista))
    }
  }
}

这是如何运作的:

scala> stackoverflow.q35804673.HeadTail.find(List(1,2,3,4,5))
res0: (Int, Int) = (1,5)

scala> stackoverflow.q35804673.HeadTail.find(List(1,5))
res1: (Int, Int) = (1,5)

scala> stackoverflow.q35804673.HeadTail.find(List(1))
res2: (Int, Int) = (1,1)

scala> stackoverflow.q35804673.HeadTail.find(List.empty)
java.lang.IllegalArgumentException: empty list

答案 1 :(得分:2)

这是因为您错过了代码中的match语句,即它应该是

def find(lista: List[Int]): (Int, Int) = lista match {
  //cases go here
}

你也有一些提取器问题(元组与List不匹配)  所以前几个案例陈述应该是,

{
  case h :: Nil => (h, h)
  case h1 :: h2 :: Nil => (h1, h2)
  ...
}

您在错过match时实际执行的操作是将PartialFunction转换为Function。它将输入类型推荐给Any的原因是因为前两个case语句与元组匹配而不是List,因此它将类型扩展为Any

最终代码是,

def find(lista: List[Int]) : (Int,Int) = lista match {
    case h :: Nil => (h, h)
    case h1 :: h2 :: Nil => (h1, h2)
    case hd :: _ :: tail => find(tail)
 }