Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the conceptual purpose of the Tuple2?

take this as a follow up to this SO question

I'm new to scala and working through the 99 problems. The given solution to p9 is:

object P09 {
  def pack[A](ls: List[A]): List[List[A]] = {
    if (ls.isEmpty) List(List())
    else {
      val (packed, next) = ls span { _ == ls.head }
      if (next == Nil) List(packed)
      else packed :: pack(next)
    }
  }
}

The span function is doing all the work here. As you can see from the API doc (it's the link) span returns a Tuple2 (actually the doc says it returns a pair - but that's been deprecated in favor or Tuple2). I was trying to figure out why you don't get something back like a list-of-lists or some such thing and stumbled across the SO link above. As I understand it, the reason for the Tuple2 has to do with increasing performance by not having to deal with Java's 'boxing/unboxing' of things like ints into objects like Integers. My question is

1) is that an accurate statement?

2) are there other reasons for something like span to return a Tuple2?

thx!

like image 352
snerd Avatar asked Jan 18 '26 16:01

snerd


2 Answers

A TupleN object has at least two major differences when compared to a "standard" List+:

  • (less importantly) the size of the tuple is known beforehand, allowing to better reason about it (by the programmer and the compiler).
  • (more importantly) a tuple preserves the type information for each of its elements/"slots".

Note that, as alluded, the type Tuple2 is a part of the TupleN family, all utilizing the same concept. For example:

scala> ("1",2,3l)
res0: (String, Int, Long) = (1,2,3)

scala> res0.getClass
res1: Class[_ <: (String, Int, Long)] = class scala.Tuple3

As you can see here, each of the elements in the 3-tuple has a distinct type, allowing for better pattern matching, stricter type protection etc.

+heterogeneous lists are also possible in Scala, but, so far, they're not part of the standard library, and arguably harder to understand, especially for newcomers.

like image 190
mikołak Avatar answered Jan 21 '26 08:01

mikołak


span returns exactly two values. A Tuple2 can hold exactly two values. A list can contain arbitrarily many values. Therefore Tuple2 is just a better fit than using a list.

like image 42
sepp2k Avatar answered Jan 21 '26 08:01

sepp2k