scala - 列表模式匹配返回每个其他元素的新列表
问题描述
我需要编写一个函数,该函数采用 ("1","2","3") 之类的列表,并使用模式匹配将该列表中的所有其他元素返回到一个新列表中。获取列表的头元素然后找到所有其他元素的正确 case 语句是什么。
def everyOther[A](list: List[A]): List[A] =
list match {
case _ => Nil
case x::xs =>
}
它应该返回从头元素开始的每个第二个元素的新列表
解决方案
递归救援。
def everyOther[A](list: List[A]): List[A] = list match {
case Nil => list
case _ :: Nil => list
case x :: _ :: xs => x :: everyOther(xs)
}
推荐阅读
- r - 在 r 中动画制图时在 gganimate 中出现旧的 api 错误
- java - javax:将json数组映射到对象列表
- android - 任务 ':app:minifyReleaseWithR8' 执行失败。无法约束类型:@Null NULL 值:... 通过约束:INT
- javascript - Polarion SDK:在工作流程上下文中设置文档名称
- android - TextView.setText 不更新
- c++ - C++ 输入验证 - 程序正在读取错误的值/未读取值
- sql - SQL Server 更新使用三表连接
- excel - Excel VBA - 从一系列单元格中复制并粘贴到一个单元格中
- samba - 将安装在 linux(CentOS 裸机)上的 zfs 池与 mac OS 和 windows 集成?
- python-3.x - 为什么我的 Python 程序在我不期望的地方打印括号和引号?