Skip to content

Instantly share code, notes, and snippets.

@swizzard

swizzard/pv.clj

Created Jun 28, 2017
Embed
What would you like to do?
PVector
(ns noc.pv)
(defprotocol IPVec
(x [x] "get X")
(y [y] "get Y")
(z [z] "get Z"))
(extend-protocol IPVec
clojure.lang.PersistentVector
(x [v] (first v))
(y [v] (second v))
(z [v] (try (nth v 2)
(catch Exception e 0.0)))
clojure.lang.PersistentArrayMap
(x [m] (get m :x))
(y [m] (get m :y))
(z [m] (get m :z 0.0)))
(defrecord PV [^Double x ^Double y ^Double z]
IPVec
(x [_] x)
(y [_] y)
(z [_] z))
(defn make-pv
([] (->PV 0.0 0.0 0.0))
([x y] (->PV x y 0.0))
([x y z] (->PV x y z)))
(defn- on [f accessor]
(fn [x1 x2] (f (accessor x1) (accessor x2))))
(defn add-pv
([p1 p2] (make-pv ((on + x) p1 p2) ((on + y) p1 p2) ((on + z) p1 p2)))
([p1 & ps] (reduce add-pv p1 ps)))
(defn sub-pv
([p1 p2] (make-pv ((on - x) p1 p2) ((on - y) p1 p2) ((on - z) p1 p2)))
([p1 & ps] (reduce sub-pv p1 ps)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.