Search This Blog

Sunday, April 7, 2013

Destructuring


;; Destructuring 

;; One of Clojure's great strengths is the ability to create maps ad-hoc and to deal with them easily.

;; You can create an ad-hoc structure with named fields:

{:a 3 :b 1}

;; And unpack it, providing defaults for its values if they are not present, as easily as:

(defn add-maps [{:keys [a b] :or {a 0 b 0} }]
  (+ a b))

(add-maps {:a 3 :b 1}) ;-> 4
(add-maps {:a 3}) ;-> 3
(add-maps {}) ;-> 0
(add-maps {:c "hello"}) ;-> 0

;; I love this and use it all the time. It's well worth learning the syntax.

;; Try playing with this expression:
(take 5 (iterate (fn [{:keys[a b] :or {b 55} :as m}] {:a a :b b :m m}) {:a 0 :b 0}))





Friday, April 5, 2013

simple-plotter

It occured to me that I was never actually going to get round to finishing off the simple plotter like I said I would. So I just pushed it to clojars and github as is. I find it pretty useful, and I've never been motivated to change it much from its current form.




http://github.com/johnlawrenceaspden/simple-plotter


[simple-plotter "0.1.1-SNAPSHOT"]


;; Barnsley's Famous Fern
;; generated by an iterated function system.

(use 'simple-plotter.core)

(defn transform [[xx xy yx yy dx dy]]
  (fn [[x y]] [(+ (* xx x) (* xy y) dx)
               (+ (* yx x) (* yy y) dy)]))

(def barnsleys-fern '((2  [  0    0     0     0.16 0 0    ])
                      (6  [  0.2 -0.26  0.23  0.22 0 0    ])
                      (7  [ -0.15 0.28  0.26  0.24 0 0.44 ])
                      (85 [  0.85 0.04 -0.004 0.85 0 1.6  ])))

(defn choose [lst] (let [n (count lst)] (nth lst (rand n))))

(defn iteration [transforms]
  (let [transform-list (mapcat (fn [[n t]] (repeat n (transform t))) transforms)]
    (fn [x] ((choose transform-list) x))))

(def barnsley-points (iterate (iteration barnsleys-fern) [0 1]))

(create-window "Barnsley's Fern" 350 450)

(ink green)
(scaled-scatter-plot (take 10000 barnsley-points) 50 300 50 400 100)


Followers