Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Scalas Product.productIterator supposed to do?

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

(I have read the (absolutely minimal) description of Scala's Product and the productIterator method on http://www.scala-lang.org/api/current/index.html#scala.Product )

like image 404
holbech Avatar asked Jun 30 '15 11:06

holbech


1 Answers

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

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.

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))
like image 127
Kolmar Avatar answered Nov 10 '22 23:11

Kolmar