Created
January 19, 2012 16:07
-
-
Save patrickgombert/1640806 to your computer and use it in GitHub Desktop.
Clojure protocols, types, and records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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