神刀安全网

In Clojure, records are wacky maps #cljklipse @viebel

In 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 defrecord .

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 clojurescript .

In Clojure, records are wacky maps #cljklipse @viebel

We were very honoured when Michał encouraged us to write a blog post on the topic usingKLIPSE.

Introduction

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

In clojure , defrecord , deftype and defprotocol were introduced in version 1.2

In 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: (A.) , (->A) and (map->A) .

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:

In clojurescript , the hash function doesn’t take the record type into account.

Maps

At first glance, records behave like maps: keyword access, get , count , keys and iteration work as expected.

But records are not real maps. Michał called them Wacky maps .

Wacky maps

Here are the differences between records and maps:

  • Unlike a regular map, a record is not callable as a function.
  • When you assoc a record you get another record.
  • When you dissoc basis keys in a record you get a map instead of a record.
  • In clojure boxing 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.)

Behind the scenes : defrecord’s transpiled javascript code

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 javascript code of defrecord :

You might find it more convenient to open defrecord’s transpiled code in a separate tab.

In a subsequent article, we will explore deftype

Clojure & Clojurescript rock!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » In Clojure, records are wacky maps #cljklipse @viebel

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址