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

Jabavu Adams picture Jabavu Adams · Sep 17, 2010 · Viewed 21.9k times · Source

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

Answer

Jabavu Adams picture Jabavu Adams · Sep 17, 2010

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