Solutions to Scala with Cats: Chapter 3
April 3, 2023These are my solutions to the exercises of chapter 3 of Scala with Cats.
Table of Contents
- Exercise 3.5.4: Branching out with Functors
- Exercise 3.6.1.1: Showing off with Contramap
- Exercise 3.6.2.1: Transformative Thinking with imap
Exercise 3.5.4: Branching out with Functors
A Functor
for Tree
can be implemented as follows:
Note that the implementation above is not stack-safe, but I didn’t worry to much
about it. We can check that the implementation works as expected by using map
over some Tree
instances:
On the above, we won’t be able to call map
directly over instances of Branch
or Leaf
because we don’t have Functor
instances in place for those types. To
make the API more friendly, we can add smart constructors to Tree
(i.e.
branch
and leaf
methods that return instances of type Tree
).
Exercise 3.6.1.1: Showing off with Contramap
To implement the contramap
method, we can create a Printable
instance that
uses the format
of the instance it’s called on (note the self
reference) and
uses func
to transform the value to an appropriate type:
With this contramap
method in place, it becomes simpler to define a
Printable
instance for our Box
case class:
Exercise 3.6.2.1: Transformative Thinking with imap
To implement imap
for Codec
, we need to rely on the encode
and decode
methods of the instance imap
is called on:
Similarly to what’s described in the chapter, we can create a Codec
for
Double
by piggybacking on the Codec
for String
that we already have in
place:
When implementing the Codec
for Box
, we can use imap
and describe how to
box and unbox a value, respectively: