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:
(defrecordDuration[minsec])
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:
(defprotocolSpecialNumber(plus[thisother])(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:
(defrecordDuration[minsec]SpecialNumber(plus[thisother]"Just add minutes and seconds part, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access