开发者

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

开发者 https://www.devze.com 2023-01-20 05:16 出处:网络
A lot of sample Scala code contains Strings and Collections named \"xs\". Why xs? Examples: var xs = List(1,2,3)开发者_运维问答

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:

  1. X is a common placeholder name.
  2. XS is pronounced X'es, i.e "many X".


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.

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消