Created
January 14, 2012 04:06
-
-
Save noahlz/1610229 to your computer and use it in GitHub Desktop.
Notes from Joy of Clojure - Chapter 7 - Functional Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Example of using comp | |
(map (comp keyword #(.toLowerCase %) name) '(a B C)) | |
;=> (:a :b :c) | |
;; equpivalent code using -> (but which doesn't use functions as data. | |
(map #(-> % (name) (.toLowerCase) (keyword)) '[a B C]) | |
;=> (:a :b :c) | |
;; Using partial | |
((partial + 5) 100 200) | |
;=> 305 | |
;; equivalent | |
(#(apply + 5 %&) 100 200) | |
;=> 305 | |
;;;;;; IMPORTANT POINT | |
;; Most collection processing can be performed with some combination of the following functions: | |
;; map, reduce, filter, for, some, repeatedly, sort-by, keep, take-while, drop-while | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; My own example of functional constraints | |
(defn ++ [n] (inc n)) | |
;=> #'user/++ | |
(defn ensure-number [f x] | |
{:pre [(number? x)]} | |
(f x)) | |
;=>#'user/ensure-number | |
(++ 1) | |
;=> 2 | |
(ensure-number ++ 1) | |
;=> 2 | |
user> (ensure-number ++ {}) | |
;=> Assert failed: (number? x) | |
; [Thrown class java.lang.AssertionError] | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; Closures in Clojure | |
(defn bot [x y bearing-num] | |
{:coords [x y] | |
:bearing ([:north :east :south :west] bearing-num) | |
:forward (fn [] (bot (+ x (:x (bearings bearing-num))) | |
(+ y (:y (bearings bearing-num))) | |
bearing-num)) | |
:turn-left (fn [] (bot x y (mod (+ 1 bearing-num) 4))) | |
:turn-right (fn [] (bot x y (mod (- 1 bearing-num) 4)))}) | |
;=> #'user/bot | |
(:bearing ((:forward ((:forward ((:turn-right (bot 5 5 0)))))))) | |
;=> :east | |
(:coords ((:forward ((:forward ((:turn-right (bot 5 5 0)))))))) | |
;=> [7 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment