如何在 Common Lisp 中递增或递减一个数字?

发布于 2024-09-19 16:24:40 字数 51 浏览 7 评论 0原文

Common Lisp 递增/递减数字和/或数值变量的惯用方法是什么?

What is the idiomatic Common Lisp way to increment/decrement numbers and/or numeric variables?

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

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

发布评论

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

评论(1

栩栩如生 2024-09-26 16:24:40

如果您只想使用结果而不修改原始数字(参数),请使用内置的“+”或“-”函数或其简写“1+”或“1-”。如果您确实想修改原始位置(包含数字),请使用内置的“incf”或“decf”函数。

使用加法运算符:

(setf num 41)
(+ 1 num)   ; returns 42, does not modify num
(+ num 1)   ; returns 42, does not modify num
(- num 1)   ; returns 40, does not modify num
(- 1 num)   ; NOTE: returns -40, since a - b is not the same as  b - a

或者,如果您愿意,可以使用以下简写:

(1+ num)    ; returns 42, does not modify num.
(1- num)    ; returns 40, does not modify num. 

请注意,Common Lisp 规范将上述两种形式定义为在含义上等效,并建议实现使它们在性能上等效。虽然这是一个建议,但根据 Lisp 专家的说法,任何“自重”的实现都应该不会出现性能差异。

如果你想更新 num (不仅仅是获取 1 + 它的值),那么使用“incf”:

(setf num 41)
(incf num)  ; returns 42, and num is now 42.

(setf num 41)
(decf num)  ; returns 40, and num is now 40.

(incf 41)   ; FAIL! Can't modify a literal

注意:

你还可以使用 incf/decf 来增加(减少)超过 1 个单位:

(setf foo 40)
(incf foo 2.5)  ; returns 42.5, and foo is now 42.5

有关更多信息,请参阅 Common Lisp超规格:
1+
incf/decf

Use the built-in "+" or "-" functions, or their shorthand "1+" or "1-", if you just want to use the result, without modifying the original number (the argument). If you do want to modify the original place (containing a number), then use the built-in "incf" or "decf" functions.

Using the addition operator:

(setf num 41)
(+ 1 num)   ; returns 42, does not modify num
(+ num 1)   ; returns 42, does not modify num
(- num 1)   ; returns 40, does not modify num
(- 1 num)   ; NOTE: returns -40, since a - b is not the same as  b - a

Or, if you prefer, you could use the following short-hand:

(1+ num)    ; returns 42, does not modify num.
(1- num)    ; returns 40, does not modify num. 

Note that the Common Lisp specification defines the above two forms to be equivalent in meaning, and suggests that implementations make them equivalent in performance. While this is a suggestion, according to Lisp experts, any "self-respecting" implementation should see no performance difference.

If you wanted to update num (not just get 1 + its value), then use "incf":

(setf num 41)
(incf num)  ; returns 42, and num is now 42.

(setf num 41)
(decf num)  ; returns 40, and num is now 40.

(incf 41)   ; FAIL! Can't modify a literal

NOTE:

You can also use incf/decf to increment (decrement) by more than 1 unit:

(setf foo 40)
(incf foo 2.5)  ; returns 42.5, and foo is now 42.5

For more information, see the Common Lisp Hyperspec:
1+
incf/decf

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