Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 354
Jabavu Adams Avatar asked Sep 17 '10 14:09

Jabavu Adams


People also ask

What is SETQ in Lisp?

(setq var1 form1 var2 form2 ...) is the simple variable assignment statement of Lisp. First form1 is evaluated and the result is stored in the variable var1, then form2 is evaluated and the result stored in var2, and so forth. setq may be used for assignment of both lexical and dynamic variables.

What is #' used in LISP?

#'functionname in Common Lisp Above defines a local variable FOO and a local function FOO . The list statement returns the value of FOO , then the function value of foo using the (function ...) notation, then the same using the short hand notation and then the value of actually calling the function FOO .


1 Answers

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

like image 145
Jabavu Adams Avatar answered Sep 28 '22 04:09

Jabavu Adams