Clojure基本语法
Clojure
的代码是由一个一个form组成的,form
可以是基本的数据结构,譬如number
,string
等,也可以是一个operation
,对于一个operation
来说,合法的结构如下:
第一个是operator
,后面的就是该operator
的参数,譬如(+ 1 2 3)
,operator
就是“+”, 然后参数为1, 2, 3,如果我们执行这个form
,得到的结果为6。
Control Flow
Clojure
的control flow
包括if
,do
和when
。
(if boolean-form
then-form
optional-else-form)
如果boolean-form
为true
,就执行then-form
,否则执行optional-else-form
,一些例子:
user=> (if false "hello" "world")
"world"
user=> (if true "hello" "world")
"hello"
user=> (if true "hello")
nil
通过上面的if
可以看到,我们的then
或者else
只有一个form
,但有时候,我们需要在这个条件下面,执行多个form
,这时候就要靠do
了。
在上面这个例子,我们使用do
来封装了多个form
,如果为true
,首先打印true
,然后返回“hello”这个值。
user=> (when true
#_=> (println "true")
#_=> (+ 1 2))
true
3
Clojure
使用nil
和false
来表示逻辑假,而其他的所有值为逻辑真,譬如:
user=> (if nil "hello" "world")
"world"
user=> (if "" "hello" "world")
"hello"
user=> (if 0 "hello" "world")
"hello"
user=> (if true "hello" "world")
user=> (if false "hello" "world")
"world"
我们可以通过nil?
来判断一个值是不是nil
,譬如:
也可以通过=来判断两个值是否相等:
user=> (= 1 1)
true
user=> (= 1 2)
false
user=> (= nil false)
false
user=> (= false false)
true
user=> (or nil 1)
1
user=> (or nil false)
false
user=> (and nil false)
nil
user=> (and 1 false 2)
false
2
我们可以通过将一个变量命名,便于后续使用,譬如: