scala - scala:附加两个列表
问题描述
我有以下 scala 代码片段:
def append(as: List[Int], bs: List[Int]): List[Int] = as match {
case Nil => bs
case x::xs => x::append(xs, bs)
}
我不明白x::
该行在哪里x::append(xs, bs)
。我知道当列表as
为空时,bs
将被返回(附加一个之前不为空的时间)。但是scala如何知道在提到的行中应该附加到as
as
as
bs
x::(..,..)
解决方案
append
如果我们脱糖一点,也许会有所帮助
def append(as: List[Int], bs: List[Int]): List[Int] =
as match {
case Nil => bs
case ::(x, xs) =>
val list = append(xs, bs)
list.::(x)
}
注意如何::
出现两次,但是第一个在
case ::(x, xs)
实际上是一个case class,尽管它的符号名称看起来很奇怪,它的声明看起来有点像这样
case class :: (head: A, next: List[A])
而另一方面,第二::
个
list.::(x)
实际上是一种右关联方法,Adds an element at the beginning of this list
看起来像这样
def :: (elem: B): List[B]
请注意如何在正确的参数上调用x :: list
等效list.::(x)
而不是x.::(list)
含义。::
推荐阅读
- javascript - 关于画布动画和设备运动的问题
- java - 如何在文本视图的文本周围设置边框
- google-apps-script - 如何将链接附加到 Apps Script 上的形状或文本框?
- php - 如何使用php从数据库中显示当前登录用户的用户名
- sql - 按提供者汇总的支付总额的前 10 名,按状态分区 - PostgreSQL
- sql - 错误数量或类型的参数错误使用带参数的游标
- sql - 如何避免使用 SQL ORACLE 分组
- laravel - 如何对 Octobercms 列表顶部的精选博客文章进行排序
- unicode - Moviepy v1.0.1 和 v1.0.0 无法在 Ubuntu 上打开 unicode 文件名。但 Mac 工作
- c# - 将 json 格式的数据转换为带有奇怪数组的 c# 类