views:

248

answers:

4

A lot of sample Scala code contains Strings and Collections named "xs" Why xs? Anything to do with the xs: used in XML (for Schema?)

Examples:

var xs = List(1,2,3)
val xs = "abc"
+18  A: 

xs is the plural of x.

Ken Bloom
I thought it was xii ;)
Paul Ruane
@Paul - no, that works only when you have exactly 12 xs
oxbow_lakes
+7  A: 

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
+13  A: 

It has nothing to do with XML. 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".
voxcogitatio
+5  A: 

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

eed3si9n
I mentally pronounce the "xs" as "excess", as in "the rest".
nibot