Skip to content

Commit

Permalink
Logic Tests You Can Use on Collections
Browse files Browse the repository at this point in the history
  • Loading branch information
kang-hyungu committed Dec 7, 2015
1 parent 51c85e6 commit d43cbea
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion src/wonderland/chapter_2.clj
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,48 @@
(= :drinkme :drinkme)
(= :drinkme 4)
(= '(:drinkme :bottle) [:drinkme :bottle])
(not= :drinkme :4)
(not= :drinkme :4)

; Logic Tests You Can Use on Collections
(empty? [:table :door :key])
(empty? [])
(empty? {})
(empty? '())

(defn empty?
[coll] (not (seq coll)))

(seq [1 2 3])
(class [1 2 3])
(class (seq [1 2 3]))
(seq [])
(empty? [])
(seq [])

; Remember, use seq to check for not empty instead of (not (empty? x)).
; This is because nil is treated as logically false in tests,
; whereas a non-nil value like [1 3 4] is treated as logically true.

(every? odd? [1 3 5])
(every? odd? [1 2 3 4 5])

; A predicate is just a function that returns a value used in a logic test.

(defn drinkable? [x]
(= x :drinkme))

(every? drinkable? [:drinkme :drinkme])
(every? drinkable? [:drinkme :poison])
(every? (fn [x] (= x :drinkme)) [:drinkme :drinkme])
(every? #(= % :drinkme) [:drinkme :drinkme])

(not-any? #(= % :drinkme) [:drinkme :poison])
(not-any? #(= % :drinkme) [:poison :poison])

(some #(> % 3) [1 2 3 4 5])
(#{1 2 3 4 5} 3)
(some #{3} [1 2 3 4 5])
(some #{4 5} [1 2 3 4 5])
(some #{nil} [nil nil nil])
(some #{false} [false false false])
(some #{true} [true true true])

0 comments on commit d43cbea

Please sign in to comment.