为什么列表和字符串标识符被命名为“xs”? (Scala 和其他语言)?
许多 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
基本上它是起源于 LISP 的命名约定。其背后的基本原理是:
Basically it's a naming convention that originated in LISP. The rationale behind it is that:
xs
是x< 的复数形式/代码>.
xs
is the plural ofx
.除了
xs
是 x 的复数形式 @Ken Bloom 指出,注意 Scala 等语言如何构造List
也很重要。List
的结构为链接列表,其中容器具有对第一项和列表其余部分的引用。::
运算符(称为 cons) 将列表构造为:::
当出现在模式匹配中时也会将列表提取到第一项和列表的其余部分如下:由于这种模式随处可见,读者可以推断
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 structureList
.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.The
::
operator (called cons) constructs the list as:The
::
when appearing in pattern matching also extracts a list into the first item and the rest of the list as follows:Since this pattern appears everywhere, readers can infer that
xs
implies "the rest of the list."我在函数式编程教程中看到过这个名称用于列表变量,但不是字符串(除非字符串被视为字符列表)。
它基本上是示例中使用的虚拟名称。您可以将标量变量命名为
x
,而将列表命名为xs
,因为xs
是x
的复数形式。在生产代码中,最好有一个更具描述性的名称。您可能还会在模式与列表匹配的代码中看到这一点。例如(在 OCaml 中):
更具描述性的一对名称可能是
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 bexs
, sincexs
is the plural ofx
. 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):
A more descriptive pair of names might be
first :: rest
, but this is just an example.