Clojure基本语法

    Clojure的代码是由一个一个form组成的,form可以是基本的数据结构,譬如numberstring等,也可以是一个operation,对于一个operation来说,合法的结构如下:

    第一个是operator,后面的就是该operator的参数,譬如(+ 1 2 3)operator就是“+”, 然后参数为1, 2, 3,如果我们执行这个form,得到的结果为6。

    Control Flow

    Clojurecontrol flow包括ifdowhen

    1. (if boolean-form
    2. then-form
    3. optional-else-form)

    如果boolean-formtrue,就执行then-form,否则执行optional-else-form,一些例子:

    1. user=> (if false "hello" "world")
    2. "world"
    3. user=> (if true "hello" "world")
    4. "hello"
    5. user=> (if true "hello")
    6. nil

    通过上面的if可以看到,我们的then或者else只有一个form,但有时候,我们需要在这个条件下面,执行多个form,这时候就要靠do了。

    在上面这个例子,我们使用do来封装了多个form,如果为true,首先打印true,然后返回“hello”这个值。

    1. user=> (when true
    2. #_=> (println "true")
    3. #_=> (+ 1 2))
    4. true
    5. 3

    Clojure使用nilfalse来表示逻辑假,而其他的所有值为逻辑真,譬如:

    1. user=> (if nil "hello" "world")
    2. "world"
    3. user=> (if "" "hello" "world")
    4. "hello"
    5. user=> (if 0 "hello" "world")
    6. "hello"
    7. user=> (if true "hello" "world")
    8. user=> (if false "hello" "world")
    9. "world"

    我们可以通过nil?来判断一个值是不是nil,譬如:

    也可以通过=来判断两个值是否相等:

    1. user=> (= 1 1)
    2. true
    3. user=> (= 1 2)
    4. false
    5. user=> (= nil false)
    6. false
    7. user=> (= false false)
    8. true
    1. user=> (or nil 1)
    2. 1
    3. user=> (or nil false)
    4. false
    5. user=> (and nil false)
    6. nil
    7. user=> (and 1 false 2)
    8. false
    9. 2

    我们可以通过将一个变量命名,便于后续使用,譬如: