为什么列表和字符串标识符被命名为“xs”? (Scala 和其他语言)?

发布于 2024-09-27 09:09:09 字数 118 浏览 7 评论 0原文

许多 Scala 示例代码包含名为“xs”的字符串和集合。 为什么是xs?

示例:

var xs = List(1,2,3)
val xs = "abc"

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

Examples:

var xs = List(1,2,3)
val xs = "abc"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

紫罗兰の梦幻 2024-10-04 09:09:09

基本上它是起源于 LISP 的命名约定。其背后的基本原理是:

  1. X 是一个常见的占位符名称。
  2. XS 发音为 X'es,即“许多 X”。

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".
回梦 2024-10-04 09:09:09

除了 xs 是 x 的复数形式 @Ken Bloom 指出,注意 Scala 等语言如何构造 List 也很重要。 List 的结构为链接列表,其中容器具有对第一项和列表其余部分的引用。

alt text

:: 运算符(称为 cons) 将列表构造为:

42 :: 69 :: 613 :: Nil

:: 当出现在模式匹配中时也会将列表提取到第一项和列表的其余部分如下:

List(42, 69, 613) match {
  case x :: xs => x
  case Nil => 0
}

由于这种模式随处可见,读者可以推断 xs 意味着“列表的其余部分”。

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

稀香 2024-10-04 09:09:09

我在函数式编程教程中看到过这个名称用于列表变量,但不是字符串(除非字符串被视为字符列表)。

它基本上是示例中使用的虚拟名称。您可以将标量变量命名为 x,而将列表命名为 xs,因为 xsx 的复数形式。在生产代码中,最好有一个更具描述性的名称。

您可能还会在模式与列表匹配的代码中看到这一点。例如(在 OCaml 中):

let rec len l =
  match l with
  | [] -> 0
  | x :: xs -> 1 + len xs

更具描述性的一对名称可能是 first :: rest,但这只是一个示例。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文