A lot of sample Scala code contains Strings and Collections named "xs". Why xs?
Examples:
var xs = List(1,2,3)
val xs = "abc"
Basically it's a naming convention that originated in LISP. The rationale behind it is that:
xs
is the plural of x
.
Apart from the fact that xs
is meant to be a plural of x as @Ken Bloom points out, it's also relevant to note how languages like Scala structure List
. List
is structured as a linked list, in which the container has a reference to the first item and to the rest of the list.
The ::
operator (called cons) constructs the list as:
42 :: 69 :: 613 :: Nil
The ::
when appearing in pattern matching also extracts a list into the first item and the rest of the list as follows:
List(42, 69, 613) match {
case x :: xs => x
case Nil => 0
}
Since this pattern appears everywhere, readers can infer that xs
implies "the rest of the list."
I've seen this name used for list variables in functional programming tutorials, but not strings (except where a string is considered a list of characters).
It's basically a dummy name used in examples. You might name a scalar variable x
while a list would be xs
, since xs
is the plural of x
. In production code, it's better to have a more descriptive name.
You might also see this in code which pattern matches with lists. For example (in OCaml):
let rec len l =
match l with
| [] -> 0
| x :: xs -> 1 + len xs
A more descriptive pair of names might be first :: rest
, but this is just an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With