如何在Common Lisp中增加或减少数字? [英] How do I increment or decrement a number in Common Lisp?

查看:98
本文介绍了如何在Common Lisp中增加或减少数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

惯用通用Lisp递增/递减数字和/或数字变量的方法是什么?

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

推荐答案

如果只想使用内置的"+"或-"函数,或者它们的简写形式"1+"或"1-"结果,而无需修改原始数字(参数).如果要修改原始位置(包含数字),请使用内置的"incf"或"decf"功能.

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.

使用加法运算符:

(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. 

请注意,Common Lisp规范将上述两种形式定义为等效,并建议实现使它们在性能上等效.根据Lisp的专家的说法,尽管这是一个建议,但任何自尊"的实现都应该不会有任何性能差异.

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.

如果您要更新num(不仅获取1 +其值),请使用"incf":

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

注意:

您还可以使用incf/decf以1个单位以上的增量(减量):

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

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

For more information, see the Common Lisp Hyperspec: 1+ incf/decf

这篇关于如何在Common Lisp中增加或减少数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆