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 ( |
(toString [this] (apply str (interleave (vals this) ["+" "i"])))) |
||
(defmethod ari/+ [Complex Complex] |
(defmethod ari/+ [Complex Complex] |
||
[x y] (->Complex (+ |
[x y] (map->Complex (merge-with + x y))) |
||
(+ (:i x) (:i y)))) |
|||
(defmethod ari/+ [Complex java.lang.Number] |
(defmethod ari/+ [Complex java.lang.Number] |
||
[ |
[{:keys [r i]} y] (->Complex (+ r y) i)) |
||
(defmethod ari/- Complex |
(defmethod ari/- Complex |
||
[x] (-> |
[x] (->> x vals (map -) (apply ->Complex) |
||
(defmethod ari/* [Complex Complex] |
(defmethod ari/* [Complex Complex] |
||
[x y] (->Complex (* |
[x y] (map->Complex (merge-with * x y))) |
||
(* (:i x) (:i y)))) |
|||
(defmethod ari/* [Complex java.lang.Number] |
(defmethod ari/* [Complex java.lang.Number] |
||
[ |
[{:keys [r i]} y] (->Complex (* r y) i)) |
||
(ari/defmethod* ari / Complex |
(ari/defmethod* ari / Complex |
||
[x] (-> |
[x] (->> x vals (map /) (apply ->Complex))) |
||
(defn conj [^Complex |
(defn conj [^Complex {:keys [r i]}] |
||
(->Complex |
(->Complex r (- i))) |
||
(defn inv [^Complex |
(defn inv [^Complex {:keys [r i]}] |
||
(let [ |
(let [m (+ (* r r) (* i i))] |
||
m (+ (* r r) (* i i))] |
|||
(->Complex (/ r m) (- (/ i m))))) |
(->Complex (/ r m) (- (/ i m))))) |
||
</lang> |
</lang> |