gpt4 book ai didi

list - 为什么我们在 Scala 中创建 List 时需要 Nil?

转载 作者:行者123 更新时间:2023-12-04 02:55:04 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why is Nil required at the end of a list built using the cons operator

(3 个回答)


5年前关闭。




我有一个关于 List 的基本问题

当我尝试使用 cons 运算符创建列表时出现以下错误

scala> val someList = 1::2
<console>:10: error: value :: is not a member of Int
val someList = 1::2
^

但是如果你看看下面,只要我在末尾添加 Nil 它就可以工作..
    scala> val someList = 1::2::Nil
someList: List[Int] = List(1, 2)

我想知道为什么在我们创建列表时最后至少需要一次 Nil

Nil 是数据类型吗?还是空元素?

最佳答案

正是因为这个原因。

value :: is not a member of Int



在 Scala 中,操作符实际上是对象上的函数。在这种情况下, ::Nil 上的一个函数对象,它实际上是一个空列表对象。
scala> Nil
res0: scala.collection.immutable.Nil.type = List()

当您这样做时 1::2 , Scala 查找名为 :: 的函数在 2它没有找到。这就是为什么它因该错误而失败。

注:在 Scala 中,如果运算符的最后一个字符不是冒号,则在第一个操作数上调用该运算符。例如, 1 + 2基本上是 1.+(2) .但是,如果最后一个字符是冒号,则在右侧操作数上调用运算符。所以在这种情况下, 1 :: Nil实际上是 Nil.::(1) .由于, ::返回另一个列表对象,你可以链接它,就像这样 1 :: 2 :: Nil实际上, Nil.::(2).::(1) .

关于list - 为什么我们在 Scala 中创建 List 时需要 Nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37741565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com