Skip to content

Instantly share code, notes, and snippets.

@sunilnandihalli
Created December 26, 2010 15:47
Show Gist options
  • Select an option

  • Save sunilnandihalli/755484 to your computer and use it in GitHub Desktop.

Select an option

Save sunilnandihalli/755484 to your computer and use it in GitHub Desktop.
(ns isomorphism.complex
(:refer-clojure)
(:require [clojure.core :as c]
[clojure.contrib.math :as m]))
(defrecord complex [re im])
(defn dispatch-fn
([x y & ys] [(class x) (class y)]))
(defmulti c+ dispatch-fn)
(defmethod c+ [java.lang.Number complex] [x {:keys [im re]} & ys]
(let [l (complex. (+ re x) im)]
(if ys (apply c+ l ys) l)))
(defmethod c+ [complex java.lang.Number] [x y & ys]
(apply c+ y x ys))
(defmethod c+ [complex complex] [{im1 :im re1 :re} {im2 :im re2 :re} & ys]
(let [l (complex. (+ re1 re2) (+ im1 im2))]
(if ys (apply c+ l ys) l)))
(defmethod c+ [java.lang.Number java.lang.Number] [x y & ys]
(let [l (+ x y)]
(if ys (apply c+ l ys) l)))
(defmulti c- dispatch-fn)
(defmethod c- [java.lang.Number complex] [x {:keys [im re]} & ys]
(let [l (complex. (- re x) im)]
(if ys (apply c- l ys) l)))
(defmethod c- [complex java.lang.Number] [x y & ys]
(apply c- y x ys))
(defmethod c- [complex complex] [{im1 :im re1 :re} {im2 :im re2 :re} & ys]
(let [l (complex. (- re1 re2) (- im1 im2))]
(if ys (apply c- l ys) l)))
(defmethod c- [java.lang.Number java.lang.Number] [x y & ys]
(let [l (- x y)]
(if ys (apply c- l ys) l)))
(defmulti c* dispatch-fn)
(defmethod c* [java.lang.Number complex] [x {:keys [im re]} & ys]
(let [l (complex. (* re x) (* im x))]
(if ys (apply c* l ys) l)))
(defmethod c* [complex java.lang.Number] [x y & ys]
(apply c* y x ys))
(defmethod c* [complex complex] [{im1 :im re1 :re} {im2 :im re2 :re} & ys]
(let [l (complex. (- (* re1 re2) (* im1 im2))
(+ (* im1 re2) (* im2 re1)))]
(if ys (apply c* l ys) l)))
(defmethod c* [java.lang.Number java.lang.Number] [x y & ys]
(let [l (* x y)]
(if ys (apply c* l ys) l)))
(defmulti conjugate class)
(defmethod conjugate complex [{:keys [re im]}]
(complex. re (- 0 im)))
(defmulti cd dispatch-fn)
(defmethod cd [java.lang.Number complex] [x {:keys [im re] :as y} & ys]
(let [l (c* (conjugate y) (/ x (+ (* im im) (* re re))))]
(if ys (apply cd l ys) l)))
(defmethod cd [complex java.lang.Number] [{:keys [re im]} y & ys]
(let [l (complex. (/ re y) (/ im y))]
(if ys (apply cd l ys) l)))
(defmethod cd [complex complex] [{im1 :im re1 :re :as x} {im2 :im re2 :re :as y} & ys]
(let [absy (+ (* im2 im2) (* re2 re2))
{:keys [re im]} (c* x (conjugate y))
l (complex. (/ re absy) (/ im absy))]
(if ys (apply cd l ys) l)))
(defmethod cd [java.lang.Number java.lang.Number] [x y & ys]
(let [l (/ x y)]
(if ys (apply cd l ys) l)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment