在 Lisp 中,函数 1+ 只是语法糖吗?
In Lisp is the function `1+` just syntactic sugar?
我刚开始学习 Lisp。要掌握的第一个概念似乎是前缀符号(即不是写“1 + 2”,而是写“+ 1 2”)。所以我想弄清楚 1+
函数存在的原因。
选择(+ 1 2)
或(1+ 2)
的原因是什么?
只是语法糖吗?是为了代码优化?是为了可读性吗?
也许有更复杂的函数调用示例可以说明 1+
函数存在的原因。任何见解将不胜感激。
请记住 Common Lisp 的一部分正在标准化许多实现已经拥有的东西。因此,如果许多实现已经具有 1+ 函数,那么包含它就足够了。 在 哪些 实现中引用了 CLtL2(MacLisp 和 Lisp Machine Lisp)。但是为什么这些实现首先要有它呢?它在循环中很有用,例如
(do ((x 0 (1+ x)))
((= x 10))
; ...
)
那是 (+ x 1) 也不错的地方。但是在很多情况下,间接调用这种函数很方便,(mapcar '1+ …) 比 (mapcar (lambda ( x) (+ 1 x)) …)。
但仅此而已。加一(或减一;也有 1-)是一个很常见的操作,有一个函数可以很方便地完成它。如果有硬件支持,它也可能是实现可以优化的东西。 (虽然 the documentation does note that "implementors are encouraged to make the performance of [(1+ number) and (+ 1 number)] be the same.") Since these functions are available and widely used, they're a very good way to indicate the intent. E.g., you could make a typo and write (+ 1 x) when you meant to write (+ 2 x), but it's much less likely that you wanted to add two if you actually wrote (1+ x). These functions are idiomatic in Common Lisp (e.g., see How do I increment or decrement a number in Common Lisp?). Emacs Lisp also includes 1+ and 1-.
如果没有这种语言,它不会受到太大影响,但它会被许多不同的人重新实现很多次。例如,Racket 实现 add1 and sub1. (Also, see add1 function from scheme to R5RS.)
Common Lisp 语言:
These are included primarily for compatibility with MacLisp and Lisp Machine Lisp. Some programmers prefer always to write (+ x 1) and (- x 1) instead of (1+ x) and (1- x).
其实这可以追溯到早期的 Lisp。 1962 年的 Lisp 1.5 已经有了。这些函数被称为 ADD1
和 SUB1
.
我刚开始学习 Lisp。要掌握的第一个概念似乎是前缀符号(即不是写“1 + 2”,而是写“+ 1 2”)。所以我想弄清楚 1+
函数存在的原因。
选择(+ 1 2)
或(1+ 2)
的原因是什么?
只是语法糖吗?是为了代码优化?是为了可读性吗?
也许有更复杂的函数调用示例可以说明 1+
函数存在的原因。任何见解将不胜感激。
请记住 Common Lisp 的一部分正在标准化许多实现已经拥有的东西。因此,如果许多实现已经具有 1+ 函数,那么包含它就足够了。
(do ((x 0 (1+ x)))
((= x 10))
; ...
)
那是 (+ x 1) 也不错的地方。但是在很多情况下,间接调用这种函数很方便,(mapcar '1+ …) 比 (mapcar (lambda ( x) (+ 1 x)) …)。
但仅此而已。加一(或减一;也有 1-)是一个很常见的操作,有一个函数可以很方便地完成它。如果有硬件支持,它也可能是实现可以优化的东西。 (虽然 the documentation does note that "implementors are encouraged to make the performance of [(1+ number) and (+ 1 number)] be the same.") Since these functions are available and widely used, they're a very good way to indicate the intent. E.g., you could make a typo and write (+ 1 x) when you meant to write (+ 2 x), but it's much less likely that you wanted to add two if you actually wrote (1+ x). These functions are idiomatic in Common Lisp (e.g., see How do I increment or decrement a number in Common Lisp?). Emacs Lisp also includes 1+ and 1-.
如果没有这种语言,它不会受到太大影响,但它会被许多不同的人重新实现很多次。例如,Racket 实现 add1 and sub1. (Also, see add1 function from scheme to R5RS.)
Common Lisp 语言:
These are included primarily for compatibility with MacLisp and Lisp Machine Lisp. Some programmers prefer always to write (+ x 1) and (- x 1) instead of (1+ x) and (1- x).
其实这可以追溯到早期的 Lisp。 1962 年的 Lisp 1.5 已经有了。这些函数被称为 ADD1
和 SUB1
.