Clojure 運算符

2018-11-28 15:50 更新

運算符是一個符號,通知編譯器執(zhí)行特定的數(shù)學或邏輯操作。

Clojure有以下類型的運算符:

  • 算術運算符
  • 關系運算符
  • 邏輯運算符
  • 位運算符

-在Clojure中,運算符和操作數(shù)以下面的語法方式工作。

語法

(operator operand1 operand2 operandn)

(+ 1 2)

上述示例對數(shù)字1和2進行算術運算。

算術運算符

Clojure語言支持任何語言的正常的算術運算符。 以下是Clojure中提供的算術運算符。

操作描述
+兩個操作數(shù)相加(+ 1 2) 得到 3
-從第一個操作數(shù)中減去第二個操作數(shù)(- 2 1) 得到 1
*兩個操作數(shù)的乘法(* 2 2) 得到 4
/分子除以分母(float (/ 3 2)) 得到 1.5
inc用于將操作數(shù)的值增加1的增量運算符inc 5 得到 6
dec用于將操作數(shù)的值減1的增量運算符dec 5 得到 4
max返回其最大值的參數(shù)max 1 2 3 返回 3
min返回其最小值的參數(shù)min 1 2 3 返回 1
rem將第一個數(shù)除以第二個數(shù)的余數(shù)rem 3 2 得到 1

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def x (+ 2 2))
   (println x)
   
   (def x (- 2 1))
   (println x)
   
   (def x (* 2 2))
   (println x)
   
   (def x (float(/ 2 1)))
   (println x)
   
   (def x (inc 2))
   (println x)
   
   (def x (dec 2))
   (println x)
   
   (def x (max 1 2 3))
   (println x)
   
   (def x (min 1 2 3))
   (println x)
   
   (def x (rem 3 2))
   (println x))
(Example)

上述示例產(chǎn)生以下結(jié)果:

4
1
4
2.0
3
1
3
1
1

關系運算符

關系運算符允許比較對象。 以下是Clojure中可用的關系運算符。

操作者描述
=測試兩個對象之間的相等性(= 2 2) 得到 true
not=測試兩個對象之間的差異(not = 3 2) 得到 true
<檢查左對象是否小于右對象正確的運算符(< 2 3) 得到 true
<=檢查左對象是否小于或等于右對象的運算符(<= 2 3) 得到 true
>檢查左對象是否大于右對象的運算符(> 3 2) 得到 true
> =檢查左對象是否大于或等于右對象的運算符(>= 3 2) 得到 true 

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def x (= 2 2))
   (println x)
   
   (def x (not= 3 2))
   (println x)
   
   (def x (< 2 3))
   (println x)
   
   (def x (<= 2 3))
   (println x)
   
   (def x (> 3 2))
   (println x)
   
   (def x (>= 3 2))
   (println x))
(Example)

上述示例產(chǎn)生以下結(jié)果:

true
true
true
true
true
true

邏輯運算符

邏輯運算符用于計算布爾表達式。 以下是Groovy中可用的邏輯運算符。

操作者描述

or

這是邏輯“或”運算(or true true)會得到 true

and

這是邏輯“與”運算(and true false)會得到 false

not

這是邏輯“非”運算(not false)會得到 true

以下代碼段顯示了如何使用各種運算符。

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def x (or true true))
   (println x)
   
   (def x (and true false))
   (println x)
   
   (def x (not true))
   (println x))
(Example)

上述示例產(chǎn)生以下結(jié)果:

true
false
false

位運算符

Groovy提供了四個按位運算符。 以下是Groovy中可用的按位運算符。

這是位取反運算符
運算符運算符說明
bit-and

這是位“和”運算符

bit-or

這是位“或”運算符

bit-xor

這是位“xor”或Exclusive'or'運算符

bit-not

這是位取反運算符

以下是這些運算符的真值表。

pqp&Qp | qp ^ Q
00000
01011
11110
10011

以下代碼段顯示了如何使用各種運算符:

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def x (bit-and 00111100 00001101))
   (println x)
   
   (def x (bit-or 00111100 00001101))
   (println x)
   
   (def x (bit-xor 00111100 00001101))
   (println x)) 
(Example)

上述示例產(chǎn)生以下結(jié)果:

576
37441
36865

運算符優(yōu)先級

與LISP一般情況一樣,沒有必要擔心運算符優(yōu)先級。 這是S表達式和前綴符號的好處之一。 所有函數(shù)從左到右和從內(nèi)到外。 Clojure中的運算符只是函數(shù),并且一切都完全括起來。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號