Answers with brief explanations to Clojure Koans on equality.
Let's roll our sleeves and start real simple.
The koan is given first, brief explanation and solution follow.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1
(= __ true)
; In clojure true is true so the answer would be true
(= true true)
(= (not false) true) ; :-) unnecessary
extra
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;2
(= __ (+ 1 1))
; answer matches with exercise number
; conspiracy theorists - this is a golden opportunity :-)
(= 2 (+ 1 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= (+ 3 4) __ (+ 2 __))
; let's reduce the way we did in primary school
(= (+ 3 4) 7)
; so the expression is
(= 7 _ (+ 2 _))
; of many things possible, it is evident that
; only 7 would be equalt to 7
(= 7 7 (+ 2 _))
; and then what do you have to add to 2 to make it = to 7?
(= 7 7 (+ 2 5))
; placing back
(= (+ 3 4) 7 (+ 2 5))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= 2 2/1 __)
; Clojure reduces the fraction to their lowest factors
; 21/3 = 7 AND
; 24/20 = 6/5
(= 2 2/1 4/2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= __ (= 2 2.0))
; floats and ints have markedly different representations
; internally and generally bad idea to have computations
; like this one
(= false (= 2 2.0)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(== 2.0 2 __)
; this one is a pure value comparison
; in this case values are equivalent
; so we can use any of 4/2 2/1 2.0 or 2
(== 2.0 2 4/2)
(== 2.0 2 2/1)
(== 2.0 2 2.0)
(== 2.0 2 2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
(not= :fill-in-the-blank __))
; instructive to think of this as
; ! equals() of Java
(not= :fill-in-the-blank false)
(not= :fill-in-the-blank true))
CAn you please suggest a good book on Clojure
ReplyDelete