加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:为什么zipped方法成功使用List的元组而不是Traversable?

发布时间:2020-12-16 18:16:22 所属栏目:安全 来源:网络整理
导读:我试图在 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执行此操作时: (Trave
我试图在 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,Traversable(3,b) )

我收到以下错误:

8: error: 
No implicit view available from 
Traversable[Int] => scala.collection.IterableLike[El2,Repr2].

有人可以解释上述错误发生了什么吗?什么是视图,我如何能够实现它想要的隐含视图?

解决方法

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

但你可以:

scala> (Traversable(1,5).toIterable).zipped.foreach( (a,b) )
(1,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,5)

在这个意义上的“视图”是一个转换函数,它允许您将Traversable“视为”Iterable,而不一定与“集合视图”有关.

更新:

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

原因是Tuple2Zipped只是预先遍历第一个集合,但迭代第二个集合以便它可以在!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这样的问题,我觉得这个问题大多适合笑,虽然这是真的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读