为什么不将Nil传递给foldLeft? [英] Why doesn't passing Nil to foldLeft work?

查看:59
本文介绍了为什么不将Nil传递给foldLeft?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用foldLeft建立列表时,经常会因为不得不显式键入注入的参数而感到烦恼,并希望我可以只使用`Nil'-这是一个人为的示例:

When I build a list using foldLeft I often get annoyed at having to explicitly type the injected parameter and wish I could just use `Nil' instead - here's a contrived example:

scala> List(1,2,3).foldLeft(List[Int]())((x,y) =>  y :: x)
res17: List[Int] = List(3, 2, 1)

scala> List(1,2,3).foldLeft(Nil)((x, y) => y :: x)
<console>:10: error: type mismatch;
 found   : List[Int]
 required: scala.collection.immutable.Nil.type
              List(1,2,3).foldLeft(Nil)((x,y) =>  y :: x)

对于List[Int]来说还不错,但是一旦您开始使用自己的类的列表,几乎可以肯定会有更长的名称,甚至是元组或其他容器的列表,因此有多个您需要指定的类名,这太可怕了:

This isn't so bad with a List[Int] but as soon as you start using lists of your own classes, which are almost certainly going to have longer names, or even lists of tuples or other containers, so there are multiple class names you need to specify, it gets horrendous:

list.foldLeft(List.empty[(SomethingClass, SomethingElseClass)]) { (x,y) => y :: x }

我猜测它不起作用的原因是,尽管使用5 :: Nil之类的东西,编译器可以将空列表的类型推断为List[Int],但是当Nil作为参数传递时到foldLeft时,它没有足够的信息,到使用时它的类型已设置.但是-真的可以吗?它不能从作为第二个参数传递的函数的返回类型中推断出类型吗?

I'm guessing that the reason it doesn't work is that whereas with something like 5 :: Nil the compiler can infer the type of the empty list to be List[Int], but when Nil is passed as a parameter to foldLeft it doesn't have enough information to do so, and by the time it gets round to being used its type is set. But - is it really true that it couldn't? Could it not infer the type from the return type of the function passed as the second argument?

如果没有,是否有我不知道的更整洁的习惯用法?

And if not, is there some neater idiom I just don't know about?

推荐答案

Scalas类型推断引擎从左到右起作用-因此,scalac无法为foldLeft的第一个参数列表推断正确的类型.您必须给编译器提示要使用的类型.代替使用List[TYPE](),您可以使用List.empty[TYPE]:

Scalas type inference engine works from left to right - therefore scalac can not infer the correct type for the first parameter list of foldLeft. You have to give the compiler a hint what type to use. Instead of using List[TYPE]() you can use List.empty[TYPE]:

(List(1,2,3) foldLeft List.empty[Int]) { (x,y) =>  y :: x }
(List.empty[Int] /: List(1, 2, 3)) { (x,y) => y :: x }

这篇关于为什么不将Nil传递给foldLeft?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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