Solutions to "Scala with Cats": Chapter 6

April 5, 2023

These are my solutions to the exercises of chapter 6 of Scala with Cats.

Table of Contents

Exercise 6.3.1.1: The Product of Lists

The reason product for List produces the Cartesian product is because List forms a Monad, and product is implemented in terms of flatMap. So Semigroupal[List].product(List(1, 2), List(3, 4)) is the same as:

for {
  a <- List(1, 2)
  b <- List(3, 4)
} yield (a, b)

Which results in the Cartesian product.

Exercise 6.4.0.1: Parallel List

List does have a Parallel instance. It zips the lists instead of doing the Cartesian product. This can be exhibited by the following snippet:

import cats.instances.list._
import cats.syntax.parallel._

(List(1, 2), List(3, 4)).parTupled
// Returns List((1, 3), (2, 4)).

(List(1, 2), List(3, 4, 5)).parTupled
// Returns List((1, 3), (2, 4)).

Solutions to "Scala with Cats": Chapter 5

April 5, 2023

These are my solutions to the exercises of chapter 5 of Scala with Cats.

Table of Contents

Exercise 5.4: Transform and Roll Out

We can rewrite Response using a monad transformer as follows:

import cats.data.EitherT
import scala.concurrent.Future

type Response[A] = EitherT[Future, String, A]

We can implement getPowerLevel as follows. Note that we need an implicit ExecutionContext in scope so that we can have an instance of Functor for Future, even if we just create our Futures with Future.successful (which doesn’t need one). We are using the global ExecutionContext for convenience.

import scala.concurrent.ExecutionContext.Implicits.global

def getPowerLevel(autobot: String): Response[Int] =
  powerLevels.get(autobot) match {
    case Some(powerLevel) => EitherT.right(Future.successful(powerLevel))
    case None => EitherT.left(Future.successful(s"Autobot $autobot is unreachable"))
  }

To implement canSpecialMove we can request the power levels of each autobot and check if their sum is greater than 15. We can use flatMap on EitherT which makes sure that errors being raised on calls to getPowerLevel stop the sequencing and have canSpecialMove return a Response with the appropriate error message.

def canSpecialMove(ally1: String, ally2: String): Response[Boolean] =
  for {
    powerLevel1 <- getPowerLevel(ally1)
    powerLevel2 <- getPowerLevel(ally2)
  } yield (powerLevel1 + powerLevel2) > 15

To implement tacticalReport, we need to produce a String from a Future, so we must use Await.

import scala.concurrent.Await
import scala.concurrent.duration._

def tacticalReport(ally1: String, ally2: String): String = {
  Await.result(canSpecialMove(ally1, ally2).value, 5.seconds) match {
    case Left(msg) =>
      s"Comms error: $msg"
    case Right(true) =>
      s"$ally1 and $ally2 are ready to roll out!"
    case Right(false) =>
      s"$ally1 and $ally2 need a recharge."
  }
}

Solutions to "Scala with Cats": Chapter 4

April 4, 2023

These are my solutions to the exercises of chapter 4 of Scala with Cats.

Table of Contents

Exercise 4.1.2: Getting Func-y

We have pure and flatMap to define map. We want to start from an F[A] and get to an F[B] from a function A => B. As such, we want to call flatMap over the value. We can’t use func directly, though. However, we can produce a function that would lift our value to an F using pure (a => pure(func(a))):

trait Monad[F[_]] {
  def pure[A](a: A): F[A]

  def flatMap[A, B](value: F[A])(func: A => F[B]): F[B]

  def map[A, B](value: F[A])(func: A => B): F[B] =
    flatMap(value)(func.andThen(pure))
}

Exercise 4.3.1: Monadic Secret Identities

pure, map and flatMap for Id can be implemented as follows:

def pure[A](a: A): Id[A] =
  a

def flatMap[A, B](value: Id[A])(func: A => Id[B]): Id[B] =
  func(value)

def map[A, B](value: Id[A])(func: A => B): Id[B] =
  func(value)

Since Id[A] is just a type alias for A, we can notice that we avoid all boxing in the implementations and, due to that fact, flatMap and map are identical.

Exercise 4.4.5: What is Best?

The answer depends on what we are looking for in specific instances, but some things that the previous examples for error handling don’t cover are:

  • We can’t accumulate errors. The proposed examples all fail fast.
  • We can’t tell exactly where the error was raised.
  • It’s not easy to do error recovery.

Exercise 4.5.4: Abstracting

A possible implementation for validateAdult is the following:

import cats.{Applicative, MonadError}

def validateAdult[F[_]](age: Int)(implicit me: MonadError[F, Throwable]): F[Int] =
  if (age >= 18) Applicative[F].pure(age)
  else me.raiseError(new IllegalArgumentException("Age must be greater than or equal to 18"))
}

If age is greater than or equal to 18, we summon an Applicative for F (which we must have in scope due to MonadError) and lift the age to F. If age is less than 18, we use the MonadError instance we have in scope to lift an IllegalArgumentException to F.

Exercise 4.6.5: Safer Folding using Eval

One way to make the naive implementation of foldRight stack safe using Eval is the following:

import cats.Eval

def foldRightEval[A, B](as: List[A], acc: B)(fn: (A, B) => B): B = {
  def aux(as: List[A], acc: B): Eval[B] =
    as match {
      case head :: tail =>
        Eval.defer(aux(tail, acc)).map(fn(head, _))
      case Nil =>
        Eval.now(acc)
    }

  aux(as, acc).value
}

We defer the call to the recursive step and then map over it to apply fn, all within the context of Eval.

Exercise 4.7.3: Show Your Working

A possible rewrite of factorial so that it captures the log messages in a Writer is the following:

import cats.data.Writer

def factorial(n: Int): Writer[Vector[String], Int] = {
  slowly {
    if (n == 0)
      Writer.apply(Vector("fact 0 1"), 1)
    else
      factorial(n - 1).mapBoth { (log, res) =>
        val ans = res * n
        (log :+ s"fact $n $ans", ans)
      }
  }
}

We can show that this allows us to reliably separate the logs for concurrent computations because we have the logs for each instance captured in each Writer instance:

Await.result(Future.sequence(Vector(
  Future(factorial(5)),
  Future(factorial(5))
)).map(_.map(_.written)), 5.seconds)
// Returns Vector(
//   Vector("fact 0 1", "fact 1 1", "fact 2 2", "fact 3 6", "fact 4 24", "fact 5 120"),
//   Vector("fact 0 1", "fact 1 1", "fact 2 2", "fact 3 6", "fact 4 24", "fact 5 120")
// )

Exercise 4.8.3: Hacking on Readers

To create a type alias for a Reader that consumes a Db we want to fix the first type parameter of Reader to Db, while still leaving the result type as a type parameter:

import cats.data.Reader

type DbReader[A] = Reader[Db, A]

The findUsername and checkPassword functions can be implemented as follows:

def findUsername(userId: Int): DbReader[Option[String]] =
  Reader.apply(db => db.usernames.get(userId))

def checkPassword(username: String, password: String): DbReader[Boolean] =
  Reader.apply(db => db.passwords.get(username).contains(password))

The checkLogin method can be implemented as follows:

def checkLogin(userId: Int, password: String): DbReader[Boolean] =
  for {
    usernameOpt <- findUsername(userId)
    validLogin <- usernameOpt.map(checkPassword(_, password)).getOrElse(Reader.apply((_: Db) => false))
  } yield validLogin

We are making use of the findUsername and checkPassword methods. There are two scenarios in which checkLogin can return a false for a given Db: when the username doesn’t exist and when the password doesn’t match.

Exercise 4.9.3: Post-Order Calculator

A possible implementation of evalOne with no proper error handling is the following:

def evalOne(sym: String): CalcState[Int] = {
  def op(f: (Int, Int) => Int): CalcState[Int] = State {
    case y :: x :: rest =>
      val ans = f(x, y)
      (ans :: rest, ans)
    case _ =>
      throw new IllegalArgumentException("Insufficient stack size")
  }

  def num(value: String): CalcState[Int] = State { s =>
    val ans = value.toInt
    (ans :: s, ans)
  }

  sym match {
    case "+"   => op(_ + _)
    case "*"   => op(_ * _)
    case "-"   => op(_ - _)
    case "/"   => op(_ / _)
    case other => num(other)
  }
}

We’re not told which operands to support, so I assumed at least +, *, - and /.

For the evalAll implementation, we’re not told what to do in case the input is empty. I assumed it would be OK to just have an exception thrown (since that was the case before), and relied on reduce over the evalOne calls:

def evalAll(input: List[String]): CalcState[Int] =
  input.map(evalOne).reduce((e1, e2) => e1.flatMap(_ => e2))

The evalInput method can rely on a call to evalAll after splitting the input by whitespaces:

def evalInput(input: String): Int =
  evalAll(input.split("\\s+").toList).runA(Nil).value

Exercise 4.10.1: Branching out Further with Monads

One implementation of Monad for Tree is the following:

implicit val treeMonad: Monad[Tree] = new Monad[Tree] {
  def pure[A](a: A): Tree[A] =
    Leaf(a)

  def flatMap[A, B](fa: Tree[A])(f: A => Tree[B]): Tree[B] =
    fa match {
      case Branch(left, right) =>
        Branch(flatMap(left)(f), flatMap(right)(f))

      case Leaf(value) =>
        f(value)
    }

  def tailRecM[A, B](a: A)(f: A => Tree[Either[A, B]]): Tree[B] =
    flatMap(f(a)) {
      case Left(value) =>
        tailRecM(value)(f)

      case Right(value) =>
        Leaf(value)
    }
}

However, tailRecM isn’t tail-recursive. We can make it tail-recursive by making the recursion explicit in the heap. In this case, we’re using two mutable stacks: one of open nodes to visit and one of already visited nodes. On that stack, we use None to signal a non-leaf node and a Some to signal a leaf node.

implicit val treeMonad: Monad[Tree] = new Monad[Tree] {
  def pure[A](a: A): Tree[A] =
    Leaf(a)

  def flatMap[A, B](fa: Tree[A])(f: A => Tree[B]): Tree[B] =
    fa match {
      case Branch(left, right) =>
        Branch(flatMap(left)(f), flatMap(right)(f))

      case Leaf(value) =>
        f(value)
    }

  def tailRecM[A, B](a: A)(f: A => Tree[Either[A, B]]): Tree[B] = {
    import scala.collection.mutable

    val open = mutable.Stack.empty[Tree[Either[A, B]]]
    val closed = mutable.Stack.empty[Option[Tree[B]]]

    open.push(f(a))

    while (open.nonEmpty) {
      open.pop() match {
        case Branch(l, r) =>
          open.push(r)
          open.push(l)
          closed.push(None)

        case Leaf(Left(value)) =>
          open.push(f(value))

        case Leaf(Right(value)) =>
          closed.push(Some(pure(value)))
      }
    }

    val ans = mutable.Stack.empty[Tree[B]]

    while (closed.nonEmpty) {
      closed.pop() match {
        case None    => ans.push(Tree.branch(ans.pop(), ans.pop()))
        case Some(v) => ans.push(v)
      }
    }

    ans.pop()
  }
}

Solutions to "Scala with Cats": Chapter 3

April 3, 2023

These are my solutions to the exercises of chapter 3 of Scala with Cats.

Table of Contents

Exercise 3.5.4: Branching out with Functors

A Functor for Tree can be implemented as follows:

import cats.Functor

implicit val treeFunctor: Functor[Tree] = new Functor[Tree] {
  def map[A, B](fa: Tree[A])(f: A => B): Tree[B] =
    fa match {
      case Branch(left, right) =>
        Branch(map(left)(f), map(right)(f))

      case Leaf(value) =>
        Leaf(f(value))
    }
}

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:

import cats.syntax.functor._

val tree: Tree[Int] = Branch(Branch(Leaf(1), Leaf(2)), Branch(Leaf(3), Leaf(4)))

tree.map(_ * 2)
// Returns Branch(Branch(Leaf(2),Leaf(4)),Branch(Leaf(6),Leaf(8))).

tree.map(_.toString)
// Returns Branch(Branch(Leaf("1"),Leaf("2")),Branch(Leaf("3"),Leaf("4"))).

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:

trait Printable[A] { self =>
  def format(value: A): String

  def contramap[B](func: B => A): Printable[B] =
    new Printable[B] {
      def format(value: B): String =
        self.format(func(value))
    }
}

With this contramap method in place, it becomes simpler to define a Printable instance for our Box case class:

final case class Box[A](value: A)

object Box {
  implicit def printableBox[A](implicit p: Printable[A]): Printable[Box[A]] =
    p.contramap(_.value)
}

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:

trait Codec[A] { self =>
  def encode(value: A): String
  def decode(value: String): A
  def imap[B](dec: A => B, enc: B => A): Codec[B] =
    new Codec[B] {
      def encode(value: B): String = self.encode(enc(value))
      def decode(value: String): B = dec(self.decode(value))
    }
}

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:

implicit val doubleCodec: Codec[Double] =
  stringCodec.imap(_.toDouble, _.toString)

When implementing the Codec for Box, we can use imap and describe how to box and unbox a value, respectively:

final case class Box[A](value: A)

object Box {
  implicit def codec[A](implicit c: Codec[A]): Codec[Box[A]] =
    c.imap(Box.apply, _.value)
}

Solutions to "Scala with Cats": Chapter 2

April 3, 2023

These are my solutions to the exercises of chapter 2 of Scala with Cats.

Table of Contents

Exercise 2.3: The Truth About Monoids

For this exercise, rather than defining instances for the proposed types, I defined instances for Cats’ Monoid directly. For that purpose, we need to import cats.Monoid.

For the Boolean type, we can define 4 monoid instances. The first is boolean or, with combine being equal to the application of the || operator and empty being false:

val booleanOrMonoid: Monoid[Boolean] = new Monoid[Boolean] {
  def combine(x: Boolean, y: Boolean): Boolean = x || y
  def empty: Boolean = false
}

The second is boolean and, with combine being equal to the application of the && operator and empty being true:

val booleanAndMonoid: Monoid[Boolean] = new Monoid[Boolean] {
  def combine(x: Boolean, y: Boolean): Boolean = x && y
  def empty: Boolean = true
}

The third is boolean exclusive or, with combine being equal to the application of the ^ operator and empty being false:

val booleanXorMonoid: Monoid[Boolean] = new Monoid[Boolean] {
  def combine(x: Boolean, y: Boolean): Boolean = x ^ y
  def empty: Boolean = false
}

The fourth is boolean exclusive nor (the negation of exclusive or), with combine being equal to the negation of the application of the ^ operator and empty being true:

val booleanXnorMonoid: Monoid[Boolean] = new Monoid[Boolean] {
  def combine(x: Boolean, y: Boolean): Boolean = !(x ^ y)
  def empty: Boolean = true
}

To convince ourselves that the monoid laws hold for the proposed monoids, we can verify them on all instances of Boolean values. Since they’re only 2 (true and false), it’s easy to check them all:

object BooleanMonoidProperties extends App {
  final val BooleanValues = List(true, false)

  def checkAssociativity(monoid: Monoid[Boolean]): Boolean =
    (for {
      a <- BooleanValues
      b <- BooleanValues
      c <- BooleanValues
    } yield monoid.combine(monoid.combine(a, b), c) == monoid.combine(a, monoid.combine(b, c))).forall(identity)

  def checkIdentityElement(monoid: Monoid[Boolean]): Boolean =
    (for { a <- BooleanValues } yield monoid.combine(a, monoid.empty) == a).forall(identity)

  def checkMonoidLaws(monoid: Monoid[Boolean]): Boolean =
    checkAssociativity(monoid) && checkIdentityElement(monoid)

  assert(checkMonoidLaws(booleanOrMonoid))
  assert(checkMonoidLaws(booleanAndMonoid))
  assert(checkMonoidLaws(booleanXorMonoid))
  assert(checkMonoidLaws(booleanXnorMonoid))
}

Exercise 2.4: All Set for Monoids

Set union forms a monoid for sets:

def setUnion[A]: Monoid[Set[A]] = new Monoid[Set[A]] {
  def combine(x: Set[A], y: Set[A]): Set[A] = x.union(y)
  def empty: Set[A] = Set.empty[A]
}

Set intersection only forms a semigroup for sets, since we can’t define an identity element for the general case. In theory, the identity element would be the set including all instances of the type of elements in the set, but in practice we can’t produce that for a generic type A:

def setIntersection[A]: Semigroup[Set[A]] = new Semigroup[Set[A]] {
  def combine(x: Set[A], y: Set[A]): Set[A] = x.intersect(y)
}

The book’s solutions suggest an additional monoid (symmetric difference), which didn’t occur to me at the time:

def setSymdiff[A]: Monoid[Set[A]] = new Monoid[Set[A]] {
  def combine(x: Set[A], y: Set[A]): Set[A] = (x.diff(y)).union(y.diff(x))
  def empty: Set[A] = Set.empty[A]
}

Exercise 2.5.4: Adding All the Things

The exercise is clearly hinting us towards using a monoid, but the first step can be defined in terms of Int only. The description doesn’t tell us what we should do in case of an empty list, but, since we’re in a chapter about monoids, I assume we want to return the identity element:

def add(items: List[Int]): Int =
  items.foldLeft(0)(_ + _)

Changing the code above to also work with Option[Int] and making sure there is no code duplication can be achieved by introducing a dependency on a Monoid instance:

import cats.Monoid

def add[A](items: List[A])(implicit monoid: Monoid[A]): A =
  items.foldLeft(monoid.empty)(monoid.combine)

With the above in place we continue to be able to add Ints, but we’re also now able to add Option[Int]s, provided we have the appropriate Monoid instances in place:

import cats.instances.int._
import cats.instances.option._

add(List(1, 2, 3))
// Returns 6.

add(List(1))
// Returns 1.

add(List.empty[Int])
// Returns 0.

add(List(Some(1), Some(2), Some(3), None))
// Returns Some(6).

add(List(Option.apply(1)))
// Returns Some(1).

add(List.empty[Option[Int]])
// Returns None.

To be able to add Order instances without making any modifications to add, we can define a Monoid instance for Order. In this case, we’re piggybacking on the Monoid instance for Double, but we could’ve implemented the sums and the production of the identity element directly:

case class Order(totalCost: Double, quantity: Double)

object Order {
  implicit val orderMonoid: Monoid[Order] = new Monoid[Order] {
    import cats.instances.double._

    val doubleMonoid = Monoid[Double]

    def combine(x: Order, y: Order): Order =
      Order(
        totalCost = doubleMonoid.combine(x.totalCost, y.totalCost),
        quantity = doubleMonoid.combine(x.quantity, y.quantity)
      )

    def empty: Order =
      Order(
        totalCost = doubleMonoid.empty,
        quantity = doubleMonoid.empty
      )
  }
}