Paste number 90329: Simple deftype/defprotocol example

Paste number 90329: Simple deftype/defprotocol example
Pasted by: stuartsierra
When:9 months, 2 weeks ago
Share:Tweet this! | http://paste.lisp.org/+1XP5
Channel:#clojure
Paste contents:
Raw Source | XML | Display As
;; Simple demonstration of deftype/defprotocol

(ns math-proto)

(defprotocol Arithmetic
  "Basic arithmetic operations"
  (add [a b] "Addition")
  (sub [a b] "Subtraction")
  (mul [a b] "Multiplication")
  (div [a b] "Division"))

;; Number is the class java.lang.Number
(extend Number Arithmetic
        {:add +, :sub -, :mul *, :div /})

(deftype Complex [#^double real #^double imaginary])

;; Protocol is a symbol, type name is a keyword
(extend ::Complex Arithmetic
        {:add (fn [a b]
                (Complex (+ (:real a) (:real b))
                         (+ (:imaginary a) (:imaginary b))))
         :sub (fn [a b]
                (Complex (- (:real a) (:real b))
                         (- (:imaginary a) (:imaginary b))))
         :mul (fn [a b]
                (Complex (- (* (:real a) (:real b))
                            (* (:imaginary a) (:imaginary b)))
                         (+ (* (:real a) (:imaginary b))
                            (* (:imaginary a) (:real b)))))})

;; Examples:

;; (add 2 3)
;;=> 5
;; (add (Complex 1 1) (Complex 2 1))
;;=> #:Complex{:real 3.0, :imaginary 2.0}
;; (mul (Complex 2 2) (Complex 3 1))
;;=> #:Complex{:real 4.0, :imaginary 8.0}

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.