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

24,263

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

Share:
24,263
Jabavu Adams
Author by

Jabavu Adams

@JabavuAdams https://github.com/jawa0

Updated on April 04, 2020

Comments

  • Jabavu Adams
    Jabavu Adams about 4 years

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