Clojure - 运算符

Clojure - 运算符 首页 / Clojure入门教程 / Clojure - 运算符

运算符是一个符号,告诉编译器执行特定的数学或逻辑运算。

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

这是按位" xor"或"异或"运算符

4

bit-not

这是按位取反运算符

以下是展示这些运算符的真值表。

pqp&qp | qp ^ q
00000
01011
11110
10011
(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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

React实战进阶45讲 -〔王沛〕

从0开始学微服务 -〔胡忠想〕

苏杰的产品创新课 -〔苏杰〕

数据中台实战课 -〔郭忆〕

如何看懂一幅画 -〔罗桂霞〕

Spark核心原理与实战 -〔王磊〕

如何成为学习高手 -〔高冷冷〕

手把手带你写一门编程语言 -〔宫文学〕

超级访谈:对话玉伯 -〔玉伯〕

好记忆不如烂笔头。留下您的足迹吧 :)