Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are List and String identifiers named "xs" (in Scala and other languages)?

A lot of sample Scala code contains Strings and Collections named "xs". Why xs?

Examples:

var xs = List(1,2,3)
val xs = "abc"
like image 495
Adrian Avatar asked Oct 14 '10 22:10

Adrian


4 Answers

Basically it's a naming convention that originated in LISP. The rationale behind it is that:

  1. X is a common placeholder name.
  2. XS is pronounced X'es, i.e "many X".
like image 94
keiter Avatar answered Nov 19 '22 22:11

keiter


xs is the plural of x.

like image 38
Ken Bloom Avatar answered Nov 19 '22 20:11

Ken Bloom


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.

alt text

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."

like image 18
Eugene Yokota Avatar answered Nov 19 '22 21:11

Eugene Yokota


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.

like image 8
Jay Conrod Avatar answered Nov 19 '22 22:11

Jay Conrod