gpt4 book ai didi

Scala:为什么压缩方法在使用 List 元组而不是 Traversable 时会成功?

转载 作者:行者123 更新时间:2023-12-04 19:06:56 27 4
gpt4 key购买 nike

我试图在 Scala 中将两个 Traversable 压缩在一起。以下示例使用 List 而不是 Traversable 执行我想要的操作:

(List(1,2,3), List(3,4,5)).zipped.foreach( (a,b) => println(a,b) )

此代码打印:
(1,3)
(2,4)
(3,5)

但是,当我尝试使用 Traversable 执行此操作时:
(Traversable(1,2,3), Traversable(3,4,5)).zipped.foreach( (a,b) => println(a,b) )

我收到以下错误:
8: error: 
No implicit view available from
Traversable[Int] => scala.collection.IterableLike[El2,Repr2].

有人可以解释上述错误是怎么回事吗?什么是 View ,我如何实现它想要的隐式 View ?

最佳答案

我已经忘记了为什么 Traversable 比 Iterable 更通用——也许这与并行集合有关,也许他们说这是一个错误,或者是一个折腾。

但你可以:

scala> (Traversable(1,2,3), Traversable(3,4,5).toIterable).zipped.foreach( (a,b) => println(a,b) )
(1,3)
(2,4)
(3,5)

补充问题是引入隐式为您做这件事是否有不利之处。

编辑:要回答您的问题,我想它看起来像以下内容,但这不是建议:
scala> implicit def `convert it`[A](t: Traversable[A]): Iterable[A] = t.toIterable
warning: there were 1 feature warning(s); re-run with -feature for details
convert$u0020it: [A](t: Traversable[A])Iterable[A]

scala> (Traversable(1,2,3), Traversable(3,4,5)).zipped.foreach( (a,b) => println(a,b) )
(1,3)
(2,4)
(3,5)

从这个意义上说,“ View ”是一种转换函数,可让您将 Traversable 视为可迭代对象,而不必与“集合 View ”有关。

更新:

查看源代码,只有第二个集合必须是可迭代的。

原因是 Tuple2Zipped只会 foreach -遍历第一个集合,但迭代第二个集合,以便它可以在 !hasNext 时停止.

有一个有趣的旧讨论,例如:

http://www.scala-lang.org/old/node/2903.html

例如,示例拉式报价:

At least implicit in the contract of a Traversable is that you can traverse it multiple times.

The best ryule for a public interface is to return a traversable when you can. You can always turn it into am iterator if you need to.



还有一个类似 this one 的问题我认为这主要是为了发笑,尽管这是事实。

关于Scala:为什么压缩方法在使用 List 元组而不是 Traversable 时会成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086557/

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