Skip to content

Instantly share code, notes, and snippets.

@francoisdevlin
Created May 25, 2010 19:26
Show Gist options
  • Save francoisdevlin/413571 to your computer and use it in GitHub Desktop.
Save francoisdevlin/413571 to your computer and use it in GitHub Desktop.
(ns user
(:require [clojure.contrib [string :as s]]))
(defprotocol PDimension
(dimensions [x]))
(defn unit [x dims]
(proxy [java.lang.Number user.PDimension]
[]
(byteValue [] (byte x))
(doubleValue [] (double x))
(floatValue [] (float x))
(intValue [] (int x))
(longValue [] (long x))
(dimensions [] dims)
(toString [] (str x " " (s/join " " (map (fn[[k v]] (str k " " v)) dims))))
))
(def area {:length 2})
(defn unit-mult
[& args]
(unit (apply * args) (apply merge-with + (map dimensions args))))
(defn unit-div
[& args]
(unit (apply / args) (apply merge-with - (map dimensions args))))
;;Everything is cool...
user=> (take 10 (iterate unit-div (unit 1 area))))
(1 :length 2
1 :length 2
1 :length 2
1 :length 2
1 :length 2
1 :length 2
1 :length 2
1 :length 2
1 :length 2
1 :length 2)
;Huh?
user=> (take 10 (iterate unit-mult (unit 1 area)))
(1 :length 2
1 :length 2 :length 2
1 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2
1 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2 :length 2)
;Weirder
user=> (map dimensions (take 10 (iterate unit-mult (unit 1 area))))
({:length 2}
{:length 2}
{:length 2}
{:length 2}
{:length 2}
{:length 2}
{:length 2}
{:length 2}
{:length 2}
{:length 2})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment