运算符是一个符号,告诉编译器执行特定的数学或逻辑运算。
Clojure具有以下类型的运算符-
注意-在Clojure中,运算符和操作数以以下语法方式工作。
(operator operand1 operand2 operandn)
(+ 1 2)
上面的示例对数字1和2进行算术运算。
Clojure语言支持普通的算术运算符,就像任何语言一样。以下是Clojure中可用的算术运算符。
| Operator | 描述 | Example |
|---|---|---|
| + | 相加 | (+ 1 2)=3 |
| - | 相减 | (- 2 1)=1 |
| * | 相乘 | (* 2 2)=4 |
| / | 相除 | (float (/3 2))=1.5 |
| inc | 递增 | inc 5=6 |
| dec | 递减 | dec 5=4 |
| max | 最大值 | max 1 2 3 will return 3 |
| min | 最小值 | min 1 2 3 will return 1 |
| rem | 余数 | rem 3 2=1 |
以下代码段显示了如何使用各种运算符。
(ns clojure.examples.hello (:gen-class)) (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)
上面的程序产生以下输出。
4 1 4 2.0 3 1 3 1 1
关系运算符允许比较对象 。以下是Clojure中可用的关系运算符。
| Operator | 描述 | Example |
|---|---|---|
| = | 判断是否相等 | (= 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)) (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)
上面的程序产生以下输出。
true true true true true true
逻辑运算符用于判断布尔表达式。
| Operator | 描述 | Example |
|---|---|---|
| and | 这是逻辑“and”运算符 | (or true true)=true |
| or | 这是逻辑“or”运算符 | (and true false)=false |
| not | 这是逻辑“not”运算符 | (not false)=true |
(ns clojure.examples.hello (:gen-class)) ;; This program displays Hello Learnfk (defn Example [] (def x (or true true)) (println x) (def x (and true false)) (println x) (def x (not true)) (println x)) (Example)
上面的程序产生以下输出。
true false false
Clojure提供了四个按位运算符。以下是Clojure中可用的按位运算符。
| Sr.No. | Operator & 描述 |
|---|---|
| 1 | bit-and 这是按位"与"运算符 |
| 2 | bit-or 这是按位"或"运算符 |
| 3 | bit-xor |
| 4 | bit-not 这是按位取反运算符 |
以下是展示这些运算符的真值表。
| p | q | p&q | p | q | p ^ q |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
| 1 | 0 | 0 | 1 | 1 |
(ns clojure.examples.hello (:gen-class)) ;; This program displays Hello Learnfk (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)
上面的程序产生以下输出。
576 37441 36865
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)