为什么在使用 cons 运算符构建的列表末尾需要 Nil [英] Why is Nil required at the end of a list built using the cons operator

查看:33
本文介绍了为什么在使用 cons 运算符构建的列表末尾需要 Nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Scala(Scala 编程,第二版,Odersky).

I'm learning Scala at the moment (Programming Scala, 2nd Edition, Odersky).

在使用 cons 操作符构建列表时,我们必须这样写:

When building a list using the cons operator we have to write:

val l = 1 :: 2 :: 3 :: 4 :: Nil

为什么我们最后需要那个 Nil?为什么编译器不能理解 4 是最后一个元素,所以只写这个:

Why do we need that Nil at the end? Why can't the compiler understand that 4 is the last element and so just write this instead:

val l = 1 :: 2 :: 3 :: 4

推荐答案

::的签名大致是:

case class ::[E](hd: E, tl: List[E]) extends List[E]

// which generates this automatically:

object :: {
    def apply[E](hd: E, tl: List[E]): ::[E]
}

Nil的签名大致是:

object Nil extends List[Nothing]

如您所见,:: 接受一个元素和一个列表.4 不是一个列表,而 Nil 是.

As you see, :: takes an element and a list. 4 is not a list, while Nil is.

这篇关于为什么在使用 cons 运算符构建的列表末尾需要 Nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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