Skip to content

Instantly share code, notes, and snippets.

@msgodf
Created April 21, 2016 07:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msgodf/566103e55535d895ad30595986c5d567 to your computer and use it in GitHub Desktop.
Save msgodf/566103e55535d895ad30595986c5d567 to your computer and use it in GitHub Desktop.
A brief example of protocols and records in Clojure
;; A protocol with a single method
(defprotocol Waggable
(wag [x]))
;; A record that implements that protocol
(defrecord Dog [name]
Waggable
(wag [x]
(prn (str (:name x)
" wagged their tail"))))
;; Call that method
(wag (->Dog "Derek"))
;; A record that doesn't implement the protocol
(defrecord Cat [name])
;; Extended to implement the protocol
(extend-protocol Waggable
Cat
(wag [x]
(prn "Cats don't wag")))
;; And then call that method
(wag (->Cat "Arnold"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment