Scalas Product.productIterator 应该做什么? [英] What is Scalas Product.productIterator supposed to do?

查看:92
本文介绍了Scalas Product.productIterator 应该做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么在使用 Tuple2[List,List]List[List] 作为我的 Product 时得到不同的结果在下面的代码中?具体来说,我想知道为什么列表列表的第二个值被包装在另一个列表中?

Can someone tell me why I am getting different results when using Tuple2[List,List] and List[List] as my Product in the code below? Specifically I would like to know why the second value of the list of lists gets wrapped in another list?

scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)

scala> val b = List(4,5,6)
b: List[Int] = List(4, 5, 6)

scala> val c = List(a,b)
c: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6))

scala> c.productIterator.foreach( println(_) )
List(1, 2, 3)
List(List(4, 5, 6)) // <-- Note this

scala> val d = (a,b)
d: (List[Int], List[Int]) = (List(1, 2, 3),List(4, 5, 6))

scala> d.productIterator.foreach( println(_) )
List(1, 2, 3)
List(4, 5, 6) // <-- Compared to this

(我在 http://www.scala-lang.org/api/current/index.html#scala.Product )

推荐答案

基本上,Tuple 表示其所有元素之间的乘积,但非空的 Listheadtail 之间的乘积.

Basically, Tuple means a product between all of its elements, but a non-empty List is a product between its head and tail.

这种情况发生在 List 上,因为所有的 case class 都扩展了 Product,并表示它们所有元素之间的乘积,类似于元组.并且非空的List被定义为一个case类,包含head和tail: final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B],它通过case class继承了Product的默认实现.

This happens for List, because all case classes extend Product, and represent a product between all their elements similar to tuples. And non-empty List is defined as a case class, containing head and tail: final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B], which inherits the default implementation of Product by case class.

您可以通过其他具有 1 个或 2 个以上元素的 List 观察到更多这种行为:

You can observe more of this behaviour with other Lists with 1 or more than 2 elements:

scala> List(a).productIterator.foreach(println)
List(1, 2, 3)
List()

scala> List(a, a).productIterator.foreach(println)
List(1, 2, 3)
List(List(1, 2, 3))

scala> List(a, a, a).productIterator.foreach(println)
List(1, 2, 3)
List(List(1, 2, 3), List(1, 2, 3))

这篇关于Scalas Product.productIterator 应该做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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