如何增加或减少Common Lisp中的数字?

Jab*_*ams 27 lisp common-lisp increment decrement

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

Jab*_*ams 38

如果您只想使用结果而不修改原始数字(参数),请使用内置的"+"或" - "函数或简写"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
Run Code Online (Sandbox Code Playgroud)

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

(1+ num)    ; returns 42, does not modify num.
(1- num)    ; returns 40, does not modify num. 
Run Code Online (Sandbox Code Playgroud)

请注意,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
Run Code Online (Sandbox Code Playgroud)

注意:

您还可以使用incf/decf递增(递减)超过1个单位:

(setf foo 40)
(incf foo 2.5)  ; returns 42.5, and foo is now 42.5
Run Code Online (Sandbox Code Playgroud)

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