Reputation: 391
Brand new to Scala so please forgive me...
Is there a reason why Scala "generally" uses zero-based indexing (e.g. Lists, Arrays, etc) but Tuples are one-based i.e. will I see a good reason for it once I get more into Scala, or is this just one of the 'quirks' you have to get used to?
Example:
val myList = List(1, 2, 3)
println(myList(0)) // returns 1
val threesome = (1, 2, 3)
println(threesome._1) // returns 1
Upvotes: 1
Views: 685
Reputation: 152
These _N numbers are one-based, instead of zero-based, because starting with 1 is a tradition set by other languages with statically typed tuples, such as Haskell and ML.
Source: Programming in Scala - Martin Odersky, Lex Spoon, Bill Venners
Upvotes: 0
Reputation: 31
This is purely for historic reasons - not sure where the first "tuple" interface came to be, but if it helps you to think about it, there isn't much of a difference between _1, _2, etc and a class that you made yourself and decided to name the parameters the same way. You can't use any functions until you know what arity tuple you're looking at already:
// nonsense code. "T >: Tuple" would mean "We want T to be a class which is a
// subtype of Tuple" if that were at all possible.
def getMemberX[T >: Tuple](aRandomSizedTuple : T, x : Int) = aRandomSizedTuple._x )
see? there isn't any value called _x in scope, so this won't compile, even in a dynamically typed language, where-as a sequence can do it:
// silly example.. but obviously works and belongs in the comparison.
def getAtX[T](xs :Seq[T], x :Int) = xs(x)
Upvotes: 0