首页 > 解决方案 > 列表模式匹配返回每个其他元素的新列表

问题描述

我需要编写一个函数,该函数采用 ("1","2","3") 之类的列表,并使用模式匹配将该列表中的所有其他元素返回到一个新列表中。获取列表的头元素然后找到所有其他元素的正确 case 语句是什么。

def everyOther[A](list: List[A]): List[A] =
     list match {
     case   _ => Nil
     case x::xs => 
}

它应该返回从头元素开始的每个第二个元素的新列表

标签: scalapattern-matching

解决方案


递归救援。

def everyOther[A](list: List[A]): List[A] = list match {
  case Nil => list
  case _ :: Nil => list
  case x :: _ :: xs => x :: everyOther(xs)
}

推荐阅读