Arithmetic/Complex: Difference between revisions

Content added Content deleted
Line 622: Line 622:
(defrecord Complex [r i]
(defrecord Complex [r i]
Object
Object
(toString [this] (str (:r this) "+" (:i this) "i")))
(toString [this] (apply str (interleave (vals this) ["+" "i"]))))


(defmethod ari/+ [Complex Complex]
(defmethod ari/+ [Complex Complex]
[x y] (->Complex (+ (:r x) (:r y))
[x y] (map->Complex (merge-with + x y)))
(+ (:i x) (:i y))))


(defmethod ari/+ [Complex java.lang.Number]
(defmethod ari/+ [Complex java.lang.Number]
[x y] (-> x :r (+ y) (->Complex (:i x))))
[{:keys [r i]} y] (->Complex (+ r y) i))


(defmethod ari/- Complex
(defmethod ari/- Complex
[x] (->Complex (- (:r x)) (- (:i x))))
[x] (->> x vals (map -) (apply ->Complex)


(defmethod ari/* [Complex Complex]
(defmethod ari/* [Complex Complex]
[x y] (->Complex (* (:r x) (:r y))
[x y] (map->Complex (merge-with * x y)))
(* (:i x) (:i y))))


(defmethod ari/* [Complex java.lang.Number]
(defmethod ari/* [Complex java.lang.Number]
[x y] (-> x :r (* y) (->Complex (:i x))))
[{:keys [r i]} y] (->Complex (* r y) i))


(ari/defmethod* ari / Complex
(ari/defmethod* ari / Complex
[x] (->Complex (/ (:r x)) (/ (:i x))))
[x] (->> x vals (map /) (apply ->Complex)))


(defn conj [^Complex x]
(defn conj [^Complex {:keys [r i]}]
(->Complex (:r x) (- (:i x))))
(->Complex r (- i)))


(defn inv [^Complex x]
(defn inv [^Complex {:keys [r i]}]
(let [r (:r x), i (:i x),
(let [m (+ (* r r) (* i i))]
m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
(->Complex (/ r m) (- (/ i m)))))
</lang>
</lang>