Skip to content

Instantly share code, notes, and snippets.

@patrickgombert
Created January 19, 2012 16:07
Show Gist options
  • Save patrickgombert/1640806 to your computer and use it in GitHub Desktop.
Save patrickgombert/1640806 to your computer and use it in GitHub Desktop.
Clojure protocols, types, and records
; Here is our protocol
(defprotocol ThirdGradeMath
(add [this])
(sub [this])
(mul [this])
(div [this]))
;And our record
(defrecord MathRecord [x y]
;Let's implement our protocol
ThirdGradeMath
;Implementing only one function
(sub [this]
(- x y)))
;Let's use make a record and get the value of y
(:y (MathRecord. 2 5))
;5
;Let's call sub on a record
(.sub (MathRecord. 1 1))
;0
;And our type
(deftype MathType [x y]
;Let's implement our protocol
ThirdGradeMath
;Implementing two functions
(add [this]
(+ x y))
(mul [this]
(* x y)))
;Let's get the value of x
(.x (MathType. 1 2))
;2
;Let's call mul
(.mul (MathType. 2 2))
;4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment