18. Datatypes - Koans Walkthrough

This video introduces datatypes, namely deftype, defrecord. These allow you to easily generate a class with named fields. defrecord only allows immutable fields, and it provides a full implementation of a Clojure map, so you can use it as a map. If you're trying to implement a data-structure that is not map-like (e.g. a vector), then you may want to use deftype instead.

Here is the 18_datatypes.clj source code:

(defrecord Nobel [prize])
(deftype Pulitzer [prize])

(defprotocol Award
  (present [this recipient]))

(defrecord Oscar [category]
  (present [this recipient]
    (print (str "Congratulations on your "
                (:category this) " Oscar, "

(deftype Razzie [category]
  (present [this recipient]

  "Holding records is meaningful only when the record is worthy of you"
  (= __ (.prize (Nobel. "peace")))

  "Types are quite similar"
  (= __ (.prize (Pulitzer. "literature")))

  "Records may be treated like maps"
  (= __ (:prize (Nobel. "physics")))

  "While types may not"
  (= __ (:prize (Pulitzer. "poetry")))

  "Further study reveals why"
  (= __
     (map map? [(Nobel. "chemistry")
                (Pulitzer. "music")]))

  "Either sort of datatype can define methods in a protocol"
  (= __
     (with-out-str (present (Oscar. "Best Picture") "Evil Alien Conquerors")))

  "Surely we can implement our own by now"
  (= "You're really the Worst Picture, Final Destination 5... sorry."
     (with-out-str (present (Razzie. "Worst Picture") "Final Destination 5"))))

Clojure Koans Walkthrough in Light Table IDE

This screencast tutorial helps you learn the Clojure programming language. Experience the joy of Clojure in the Light Table IDE as we tour through the Clojure Koans, taking you all the way from Beginner to Intermediate to Advanced.

Clojure is a Lisp created by Rich Hickey that runs on the JVM, as an alternative to Java. ClojureScript can target the web browser environment, and node.js, by compiling down to JavaScript, using the Google Closure compiler. Clojure features immutability, functional programming, and being a Lisp, macros.