concept record in category clojure

appears as: records, record, records
Clojure in Action, Second Edition

This is an excerpt from Manning's book Clojure in Action, Second Edition.

This book covers Clojure version 1.6. In the first few chapters you’ll learn the fundamentals of Clojure: its syntax, building blocks, data structures, Java interoperability, and concurrency features. As we progress beyond the basics, you’ll learn how Clojure can simplify larger programs using macros, protocols and records, and higher-order functions. By the end of this book you’ll understand why Clojure is traveling a rare path to popularity and how it can transform your approach to developing software.

Notice the call to extend-type and how you use the name of the newly defined record NewExpense instead of the previously used, more generic IPersistentMap. This shows that records can participate fully in protocols and indeed can participate in as many as needed. By the way, for completeness, it’s worth modifying the test namespace to depend on the new clj-in-act.ch9.expense-record namespace and checking to see if all tests pass. They should.

Notice how you can access the fields of the NewExpense instances using keywords. This is because defrecord creates a class that already implements several interfaces, including IPersistentMap, IKeywordLookup, and ILookup. In this manner, they work in the same way as regular Clojure maps, including with respect to destructuring, metadata, and the use of functions such as assoc and dissoc. A useful point to note is that records are extensible in that they can accept values for keys that weren’t originally specified as part of the defrecord call. The only penalty to this is that such keys have the same performance as Clojure maps. Records also implement the hashCode and equals methods, to support value-based equality out of the box. A final note is that the field specification supports type hints. By the way, it’s worth noting here that records aren’t functions, and so they can’t be used as functions when looking up values. For instance, you can look up a key inside a Clojure map by using the map as a function and the key as a parameter, but you can’t do this with records. Here’s an example to illustrate records’ maplike features:

Listing 9.6 shows how records can participate in protocols. There’s nearly no change to the code from the previous implementation in listing 9.5, but records have more direct support for protocols. They can supply the implementations of protocols inline with their definition. The following listing shows this version.

The Joy of Clojure, Second Edition

This is an excerpt from Manning's book The Joy of Clojure, Second Edition.

Another downside to OOP is the tight coupling between function and data. The Java programming language forces you to build programs entirely from class hierarchies, restricting all functionality to containing methods in a highly restrictive “Kingdom of Nouns” (Yegge 2006). This environment is so restrictive that programmers are often forced to turn a blind eye to awkward attachments of inappropriately grouped methods and classes.[16] It’s because of the proliferation of this stringent object-centric viewpoint that Java code tends toward being verbose and complex (Budd 1995). Clojure functions are data, yet this in no way restricts the decoupling of data and the functions that work on it.[17] Many of what programmers perceive to be classes are data tables that Clojure provides via maps[18] and records. The final strike against viewing everything as an object is that mathematicians view little (if anything) as objects (Abadi 1996). Instead, mathematics is built on the relationships between one set of elements and another through the application of functions.

Note that the change-age function works with either structs or records—no change is required. Only the definition and the mechanism of instantiation need to be updated.

Other noteworthy differences between maps and records include the following:

  • Records, unlike maps, can’t serve as functions.
  • Records are never equal to maps with the same key/value mappings.
  • You still look up values in records by doing (:keyword obj); it’s just that if obj is a record, this code will run dramatically faster. By the way, that means destructuring still works, as well. Records support metadata using with-meta and meta, just like other Clojure collections, and you can even redefine a record if desired to have different fields giving you the compiled performance of Java dynamically. All of these together mean you can build a lot of code on top of simple hash-map objects and then make minimal changes to switch to using records instead, gaining the performance benefits we already covered.

    You should understand records well enough to be able to reimplement the persistent binary tree from chapter 5 using defrecord instead of maps. This is shown in the following listing. Note that you have to add the defrecord and change the expressions in xconj where objects are created, but the xseq function is defined identically to how it was before.

    Listing 9.1. Persistent binary tree built from records
    (defrecord TreeNode [val l r]) #1 (defn xconj [t v] #2    (cond     (nil? t)       (TreeNode. v nil nil)     (< v (:val t)) (TreeNode. (:val t) (xconj (:l t) v) (:r t))     :else          (TreeNode. (:val t) (:l t) (xconj (:r t) v)))) (defn xseq [t] #3    (when t     (concat (xseq (:l t)) [(:val t)] (xseq (:r t))))) (def sample-tree (reduce xconj nil [3 5 2 4 6])) #4  (xseq sample-tree) ;=> (2 3 4 5 6) #1 - Define a record type #2 - Add to a tree #3 - Convert trees to seqs #4 - Try it out !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!

    You can assoc and dissoc any key you want—adding keys that weren’t defined in the defrecord works, although they have the performance of a regular map. Perhaps more surprisingly, dissocing a key given in the record works but returns a regular map rather than a record. In this example, note that the return value is printed as a plain map, not with the #:user.TreeNode prefix of a record:

    (dissoc (TreeNode. 5 nil nil) :l)
    ;=> {:val 5, :r nil}

    A final benefit of records is how well they integrate with Clojure protocols. But to fully understand how they relate, we must first explore what protocols are.

    Using records

    If you instead use a record, then the solution is as simple as this:

    (defrecord Move [from to castle? promotion]
      Object
      (toString [this]
        (str "Move " (:from this)
             " to " (:to this)
             (if (:castle? this) " castle"
               (if-let [p (:promotion this)]
                 (str " promote to " p)
                 "")))))

    As we mentioned in the previous section, in the body of a record you can take up to two actions: participate in a protocol, or override any of the methods in the java.lang.Object class. For the Move record, you override toString in order to allow it to participate in Java’s overarching polymorphic print facility:

    (str (Move. "e2" "e4" nil nil))
    ;=> "Move e2 to e4"
    
    (.println System/out (Move. "e7" "e8" nil \Q))
    ; Move e7 to e8 promote to Q

    You’ve once again gone back to positional construction using records, but as we’ll show, Clojure even has an answer for this.