Lisp - 比較運算子



下表顯示了 LISP 支援的所有用於比較數字的關係運算符。但是,與其他語言中的關係運算符不同,LISP 比較運算子可以接受兩個以上的運算元,並且它們僅適用於數字。

假設變數A的值為 10,變數B的值為 20,則 -

運算子 描述 示例
= 檢查運算元的值是否都相等,如果相等則條件為真。 (= A B) 不為真。
/= 檢查運算元的值是否都不相等,如果值不相等則條件為真。 (/= A B) 為真。
> 檢查運算元的值是否單調遞減。 (> A B) 不為真。
< 檢查運算元的值是否單調遞增。 (< A B) 為真。
>= 檢查任何左側運算元的值是否大於或等於下一個右側運算元的值,如果大於或等於則條件為真。 (>= A B) 不為真。
<= 檢查任何左側運算元的值是否小於或等於其右側運算元的值,如果小於或等於則條件為真。 (<= A B) 為真。
max 比較兩個或多個引數並返回最大值。 (max A B) 返回 20
min 比較兩個或多個引數並返回最小值。 (min A B) 返回 10

示例 - 等值比較

建立一個名為 main.lisp 的新原始碼檔案,並在其中輸入以下程式碼。

main.lisp

; set a as 10
(setq a 10)
; set b as 20
(setq b 20)

; print equality of a and b
(format t "~% A = B is ~a" (= a b))
; print non-equality of a and b
(format t "~% A /= B is ~a" (/= a b))

輸出

當您點選“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果:

A = B is NIL
A /= B is T

示例 - 大小比較

更新名為 main.lisp 的檔案,並在其中輸入以下程式碼。

main.lisp

; set a as 10
(setq a 10)

; set b as 20
(setq b 20)

; compare a with b for size and print result
(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))

輸出

當您點選“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果:

A > B is NIL
A < B is T
A >= B is NIL
A <= B is T

示例 - 最小/最大計算

更新名為 main.lisp 的檔案,並在其中輸入以下程式碼。

main.lisp

; set a as 10
(setq a 10)
; set b as 20
(setq b 20)

; compute max of a and b and print the result
(format t "~% Max of A and B is ~d" (max a b))

; compute min of a and b and print the result
(format t "~% Min of A and B is ~d" (min a b))

輸出

當您點選“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回以下結果:

Max of A and B is 20
Min of A and B is 10
lisp_operators.htm
廣告

© . All rights reserved.