Basic clojure knowledge

Basic Knowledeg

1. prefix notation

1
2
3
4
(- 3 2 1) ; => 0
(+ 1 2 3) ; => 6
(< 1 2 3) ; => true
(< 1 4 2) ; => false

2. data type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(class 1) ;=> java.lang.Long
(class 1.0) ;=> java.lang.Double
(class true) ;=> java.lang.Boolean
(class "str") ;=> java.lang.String

(class (byte 1)) ;=> java.lang.Byte
(class (short 1)) ;=> java.lang.Short
(class (int 1)) ;=> java.lang.Integer
(class (float 1.0)) ;=> java.lang.Float
(class (char 'a')) or (class \a) ;=> java.lang.Character

(class (/ 1 3)) ;=> clojure.lang.Ratio, support lazy evaluating.

(class 36786883868216818816N) ;=> clojure.lang.BigInt
(class 3.14159265358M) ;=> java.math.BigDecimal

3. expression

  • if [else]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    (if (< 1 2)
    (println "it is true")
    (println "it is false")
    ) ;=> it is true

    (if ""
    (prn "it is true")) ;=> it is true

    (if 0
    (prn "it is true")) ;=> it is true

    (if nil
    (prn "it is true")) ;=> nil!!
  • or/and
    1
    2
    (prn (or true false)) ;=> true
    (prn (and true false)) ;=> false

4. data structures

  • list
    1
    2
    3
    (list 1 2 3)
    `(1 2 3)
    ;=> (1 2 3)
  • vector
    1
    [1 2 3] ;=> [1 2 3]
  • set
    1
    #{1 2 3} ;=> #{1 2 3}
  • map
    1
    2
    3
    {:one 1,
    :two 2,
    :three 3} ;=> {:one 1, :three 3, :two 2}

5. operation on data structures

  • op list (seq access)
    1
    2
    3
    4
    5
    (def list0 `(1 2 3))
    (first list0) ;=> 1
    (rest list0) ;=> (2 3)
    (last list0) ;=> 3
    (cons 0 list0) ;=> (0 1 2 3)
  • op vector (rand access)
    1
    2
    3
    4
    (def vec0 [4 5 6])
    (nth vec0 2) ;=> 6
    (vec0 2) ;=> 6, with index.
    (concat [1 2 3] vec0) ;=> (1 2 3 4 5 6), it called sequence.
  • op set
    1
    2
    3
    (def set0 #{5 7 2 6})
    (count set0) ;=> 4
    (set0 2) ;=> 2
  • op map
    1
    2
    3
    4
    5
    6
    (def map0 {:one 1, :two 2, :three 3})
    (map0 :one) ;=> 1
    (:one map0) ;=> 1
    (merge {:four 4} map0) ;=> {:two 2, :three 3, :one 1, :four 4}

    (def map1 (sorted-map 2 :two 1 :one)) ;=> {1 :one, 2 :two}