diff --git a/ch-02/src/ch_02/functions.clj b/ch-02/src/ch_02/functions.clj index 35b37a3..1724a43 100644 --- a/ch-02/src/ch_02/functions.clj +++ b/ch-02/src/ch_02/functions.clj @@ -18,23 +18,67 @@ (defn do-map [] (println " Mapping str/lower-case") - (println (str " " (vec (map str/lower-case - ["Java" "Imperative" "Weeping" - "Clojure" "Learning" "Peace"])))) + (println (str " " (vec (map str/lower-case + ["Java" "Imperative" "Weeping" + "Clojure" "Learning" "Peace"])))) (println " Mapping *") - (println (str " " (vec (map * [1 2 3 4] [5 6 7 8]))))) + (println (str " " (vec (map * [1 2 3 4] [5 6 7 8]))))) (defn do-reduce [] (println " Reduce using max") - (println (str " " (reduce max [0 -3 10 48]))) + (println (str " " (reduce max [0 -3 10 48]))) (println " Reduce using +") - (println (str " " (reduce + 50 [1 2 3 4]))) + (println (str " " (reduce + 50 [1 2 3 4]))) (println " Reduce vector to a map") - (println (str " " (reduce (fn [m v] - (assoc m v (* v v))) - {} - [1 2 3 4])))) + (println (str " " (reduce (fn [m v] + (assoc m v (* v v))) + {} + [1 2 3 4])))) + +(def args [2 -2 10]) +(defn do-apply + [] + (println " Apply hash-map") + (println (str " " (apply hash-map [:a 5 :b 6]))) + (println " Apply using defined args") + (println (str " " (apply * 0.5 3 args))) + (println " Define a partial function")) + +(def only-strings (partial filter string?)) +(defn do-partials + [] + (println " Apply a partial function") + (println (str " " (vec (only-strings ["a" 5 "b" 7]))))) + +(defn do-literals + [] + (println " Function literals allow specifying some arguments") + (println (str " " (vec (#(filter string? %) ["a" 5 :b "b"])))) + (println " Literals can specify arguments other than first") + (println (str " " (vec (#(filter % ["a" 5 :b "b"]) string?)))) + (println " Exception if function literals specify no arguments") + (try + (#(map *) [1 2 3] [4 5 6] [7 8 9]) + (catch clojure.lang.ArityException e + (println (str " " e)) + (println " Literals specify all arguments to functions we use") + (println (str " " (vec (#(map * % %2 %3) [1 2 3] + [4 5 6] + [7 8 9])))))) + (println " Exception if function literals specify some arguments") + (try + (#(map * % %2 %3) [1 2 3] [4 5 6]) + (catch clojure.lang.ArityException e + (println (str " " e)) + (println " Literals can use rest args") + (println (str " " (vec (#(apply map * %&) [1 2 3] + [4 5 6] + [7 8 9])))))) + (println " Partial accomplishes same results as %&") + (println (str " " (vec ((partial map *) [1 2 3] + [4 5 6] + [7 8 9]))))) (defn do-all [] @@ -49,4 +93,13 @@ (do-map) (println) (println "Reduce: collection -> scalar") - (do-reduce)) + (do-reduce) + (println) + (println "Partial function applications (apply)") + (do-apply) + (println) + (println "Partial functions") + (do-partials) + (println) + (println "Partials versus function literals") + (do-literals))