運算符是一個符號,它告訴編譯器執(zhí)行特定的數(shù)學(xué)或邏輯操作。 LISP允許在眾多的數(shù)據(jù)業(yè)務(wù),通過各種函數(shù),宏和其他結(jié)構(gòu)的支持。
允許對數(shù)據(jù)的操作都可以歸類為:
算術(shù)運算
比較操作
邏輯運算
位運算
下表列出了所有支持的LISP算術(shù)運算符。假設(shè)變量A=10和變量B=20則:
運算符 | 描述 | Example |
---|---|---|
+ | 增加了兩個操作數(shù) | (+ A B) = 30 |
- | 從第一數(shù)減去第二個操作數(shù) | (- A B)= -10 |
* | 乘兩個操作數(shù) | (* A B) = 200 |
/ | 通過取消分子除以分子 | (/ B A) = 2 |
mod,rem | 模運算符和其余整數(shù)除法后 | (mod B A ) = 0 |
incf | 遞增運算符,所指定的第二個參數(shù)增加整數(shù)值 | (incf A 3) = 13 |
decf | 遞減操作符,通過指定的第二個參數(shù)減小整數(shù)值 | (decf A 4) = 9 |
例子
創(chuàng)建一個名為main.lisp一個新的源代碼文件,并在其中輸入如下代碼:
(setq a 10) (setq b 20) (format t "~% A + B = ~d" (+ a b)) (format t "~% A - B = ~d" (- a b)) (format t "~% A x B = ~d" (* a b)) (format t "~% B / A = ~d" (/ b a)) (format t "~% Increment A by 3 = ~d" (incf a 3)) (format t "~% Decrement A by 4 = ~d" (decf a 4))
當(dāng)您單擊Execute按鈕,或按下Ctrl+ E,LISP立即執(zhí)行它,返回的結(jié)果是:
A + B = 30 A - B = -10 A x B = 200 B / A = 2 Increment A by 3 = 13 Decrement A by 4 = 9
下表列出了所有支持的LISP關(guān)系運算符的數(shù)字之間進(jìn)行比較。然而不像其他語言的關(guān)系運算符,LISP的比較操作符可能需要超過兩個操作數(shù),他們在只有數(shù)字工作。
假設(shè)變量A=10和變量B=20,則:
Operator | 描述 | Example |
---|---|---|
= | 檢查如果操作數(shù)的值都相等與否,如果是的話那么條件為真。 | (= A B)= true. |
/= | 檢查如果操作數(shù)的值都不同,或沒有,如果值不相等,則條件為真。 | (/= A B) =true. |
> | 檢查如果操作數(shù)的值單調(diào)遞減。 | (> A B) !=true. |
< | 檢查如果操作數(shù)的值單調(diào)遞增。 | (< A B) = true. |
>= | 如有左操作數(shù)的值大于或等于下一個右操作數(shù)的值,如果是則條件檢查為真。 | (>= A B) !=true. |
<= | 如有左操作數(shù)的值小于或等于其右操作數(shù)的值,如果是,則條件檢查為真。 | (<= A B) = true. |
max | 它比較兩個或多個參數(shù),并返回最大值。 | (max A B) 返回20 |
min | 它比較兩個或多個參數(shù),并返回最小值。 | (min A B) 返回 20 |
示例
創(chuàng)建一個名為main.lisp一個新的源代碼文件,并在其中輸入如下代碼:
(setq a 10) (setq b 20) (format t "~% A = B is ~a" (= a b)) (format t "~% A /= B is ~a" (/= a b)) (format t "~% A > B is ~a" (> a b)) (format t "~% A < B is ~a" (< a b)) (format t "~% A >= B is ~a" (>= a b)) (format t "~% A <= B is ~a" (<= a b)) (format t "~% Max of A and B is ~d" (max a b)) (format t "~% Min of A and B is ~d" (min a b))
當(dāng)您單擊Execute按鈕,或按下Ctrl+ E,LISP立即執(zhí)行它,返回的結(jié)果是:
A = B is NIL A /= B is T A > B is NIL A < B is T A >= B is NIL A <= B is T Max of A and B is 20 Min of A and B is 10
Common Lisp中提供了三種邏輯運算符:AND,OR,而不是運算符的布爾值。假定A=nil,B=5,那么
運算符 | 描述 | 示例 |
---|---|---|
and | 這需要任意數(shù)量的參數(shù)。該參數(shù)是從左向右計算。如果所有參數(shù)的計算結(jié)果為非零,那么最后一個參數(shù)的值返回。否則就返回nil。 | (and A B) = NIL. |
or | 這需要任意數(shù)量的參數(shù)。該參數(shù)是從左向右計算的,直到一個計算結(jié)果為非零,則此情況下返回參數(shù)值,否則返回nil。 | (or A B) = 5. |
not | 它接受一個參數(shù),并返回t,如果參數(shù)的計算結(jié)果為nil。 | (not A) = T. |
示例
創(chuàng)建一個名為main.lisp一個新的源代碼文件,并在其中輸入如下代碼:
(setq a 10) (setq b 20) (format t "~% A and B is ~a" (and a b)) (format t "~% A or B is ~a" (or a b)) (format t "~% not A is ~a" (not a)) (terpri) (setq a nil) (setq b 5) (下一篇:LISP - 數(shù)字