Skip to content

Instantly share code, notes, and snippets.

@gfredericks
Last active December 22, 2015 02:49
Show Gist options
  • Save gfredericks/6406008 to your computer and use it in GitHub Desktop.
Save gfredericks/6406008 to your computer and use it in GitHub Desktop.
abstract algebra helpers
(defmacro defring
[additive-identity
multiplicative-identity
add
negate
multiply]
`(let [add# ~add
negate# ~negate
multiply# ~multiply]
(defn ~'+
([] ~additive-identity)
([x#] x#)
([x# y#] (add# x# y#))
([x# y# & zs#] (reduce add# (add# x# y#) zs#)))
(defn ~'-
([x#] (negate# x#))
([x# y#] (~'+ x# (negate# y#)))
([x# y# & zs#] (~'+ x# (negate# (apply add# zs#)))))
(defn ~'*
([] ~multiplicative-identity)
([x#] x#)
([x# y#] (multiply# x# y#))
([x# y# & zs#] (reduce multiply# (multiply# x# y#) zs#)))))
@gdeer81
Copy link

gdeer81 commented Sep 5, 2013

I don't think I'm using this properly:
(defring (range) (range) clojure.core/+ clojure.core/- clojure.core/*)

@gfredericks
Copy link
Author

Your additive identity should be 0, not (range), and the multiplicative identity should be 1, not (range).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment