With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

Chapter 7. Records and Protocols

In this chapter, you will write études that use `defprotocol` and `defrecord` to implement addition, subtraction, multiplication, and division of rational and complex numbers.

As an example, we will build a record that keeps track of a duration in terms of minutes and seconds, and implement a protocol that can add two durations and can convert a duration to a string. It is in a project named proto:

``(``defrecord ``Duration` `[``min ``sec``])``

Once you have this record defined, you can use it as follows:

```proto.core=> ;; Create a new duration of 2 minutes and 29 seconds
proto.core=> (def d (Duration. 2 29))
#proto.core.Duration{:min 2, :sec 29}
proto.core=> (:min d) ;; extract values
2
proto.core=> (:sec d)
29```

Since a duration is a special kind of number, we will implement a protocol for handling special numbers. It has two methods: `plus` (to add two special numbers) and `canonical` (to convert the special number to “canonical form.” For example, the canonical form of 2 minutes and 73 seconds is 3 minutes and 13 seconds:

````(``defprotocol ``SpecialNumber`
`(``plus` `[``this` `other``])`
`(``canonical` `[``this``]))````

The `plus` method takes two parameters: `this` record and an `other` duration. When you define protocols, the first parameter of every method is the object you are interested in manipulating.

Now you can implement these methods by adding to `defrecord`. Here is the code for `canonical`:

````(``defrecord ``Duration` `[``min ``sec``]`
`SpecialNumber`

`(``plus` `[``this` `other``]`
`"Just add minutes and seconds part, ...````

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required