36

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

Examples:

var xs = List(1,2,3)
val xs = "abc"
Adrian
  • 3,762
  • 2
  • 31
  • 40
  • Related (but probably not a duplicate) http://stackoverflow.com/questions/1564758/does-functional-programming-mandate-new-naming-conventions – Ken Bloom Oct 14 '10 at 22:33

4 Answers4

50

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".
Adrian
  • 3,762
  • 2
  • 31
  • 40
keiter
  • 3,534
  • 28
  • 38
  • 5
    The convention is actually extended to multi-dimensional structures. For example, xss may be a list of lists, and xsss may be an array of arrays of arrays. – Adrian Dec 22 '11 at 18:08
  • 2
    And why not use proper and meaningful names? – shinzou Nov 13 '17 at 18:42
31

xs is the plural of x.

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
18

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

Community
  • 1
  • 1
Eugene Yokota
  • 94,654
  • 45
  • 215
  • 319
8

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.

Jay Conrod
  • 28,943
  • 19
  • 98
  • 110
  • I tend to use same convention in production, for example "order" and "orders" ;) – bbozo Sep 25 '14 at 11:43
  • I think the use of x an xs is perfect for production code, too. The domain meaning should be inside the name of the result variable. – stackunderflow Jul 21 '18 at 10:15