How do I increment or decrement a number in Common Lisp?

送分小仙女□ 提交于 2020-01-20 17:14:46

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/3736094/how-do-i-increment-or-decrement-a-number-in-common-lisp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!