Let's look at the solutions for the next of Clojure Koans Creating Functions.
(defn square [x] (* x x))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1
(= [__ __ __] (let [not-a-symbol? (complement symbol?)]
(map not-a-symbol? [:a 'b "c"])))
; As usual, for reading such expressions, start by
; reducing them
; the combination of let and application of the newly
; created function acts on the vector [:a 'b "c"]
; but only 'b is a symbol. After complement
; we get (true false true)
(= [true false true] (let [not-a-symbol? (complement symbol?)]
(map not-a-symbol? [:a 'b "c"])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;2
(= [:wheat "wheat" 'wheat]
(let [not-nil? ___]
(filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil])))
; if you followed the previous example closely then
(= [:wheat "wheat" 'wheat]
(let [not-nil? (complement nil?)]
(filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= 20 (let [multiply-by-5 (partial * 5)]
(___ __)))
; the partial fn multiply-by-5 multiplies by 5
; we need and additonal 4
(= 20 (let [multiply-by-5 (partial * 5)]
(multiply-by-5 4)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= [__ __ __ __]
(let [ab-adder (partial concat [:a :b])]
(ab-adder [__ __])))
(= [:a :b :c :d]
(let [ab-adder (partial concat [:a :b])]
(ab-adder [:c :d])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= 25 (let [inc-and-square (comp square inc)]
(inc-and-square __)))
; what, but 4?
; because inc is to be applied along with square
(= 25 (let [inc-and-square (comp square inc)]
(inc-and-square 5)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
(= __ (let [double-dec (comp dec dec)]
(double-dec 10)))
; since dec is applied twice
(= 8 (let [double-dec (comp dec dec)]
(double-dec 10)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;7
(= 99 (let [square-and-dec
___]
(square-and-dec 10))))
; the ordering of functions is critcial
; those coming from imperative languages can vouch for this
(= 99 (let [square-and-dec (comp dec square)]
(square-and-dec 10)))
No comments:
Post a Comment