clojure , records, types and protocols are parts of the fundamental building blocks of the language.
We have unveiled
defprotocol ’s secret ina previous post. Now it’s time to explore
This article has been inspired by this great talk by Michał Marczyk: defrecord/deftype in Clojure and ClojureScript .
Michał knows this topic very deeply as he contributed to the implementation of types, records and protocols in
clojurescript in 2012.
He’s also the #4 contributor on
We were very honoured when Michał encouraged us to write a blog post on the topic usingKLIPSE.
What is a record?
In computer science, a record (also called struct or compound data) is a basic data structure. A record is a collection of fields, possibly of different data types, typically in fixed number and sequence. Wikipedia
defprotocol were introduced in version 1.2
clojurescript the persistent data structures (maps, vectors …) are based on types, records and protocols.
Records: creation and identity
There are 3 ways to create a record: a constructor and two factory functions:
You can retrieve the basis keys of the record with
getBasis that returns a vector of basis keys as symbols.
Records of the same type and same values are equal and have the same hash code.
Records of different types are never equal (even if they have the same values).
Let’s see it in action withKLIPSE:
clojurescript , the
hash function doesn’t take the record type into account.
At first glance, records behave like maps: keyword access,
keys and iteration work as expected.
But records are not real maps. Michał called them Wacky maps .
Here are the differences between records and maps:
- Unlike a regular map, a record is not callable as a function.
- When you
assoca record you get another record.
- When you
dissocbasis keys in a record you get a map instead of a record.
clojureboxing happens on records when you use type hints; but not in
clojurescript. (Boxing can be avoided with type hints, if you use field access syntax and you’re in a primitive-friendly context e.g. an arithmetic expression.)
If you are curious to see how the magic occurs in
clojurescript , you will find it very interesting to observe and meditate around the transpiled
You might find it more convenient to open defrecord’s transpiled code in a separate tab.
In a subsequent article, we will explore
Clojure & Clojurescript rock!
转载本站任何文章请注明：转载至神刀安全网，谢谢神刀安全网 » In Clojure, records are wacky maps #cljklipse @viebel