Blankman
Blankman

Reputation: 267030

Why does a generic type class representing a Tree have A and B types?

In the book essential scala they have an example of representing a Tree using Generics/Types.

What I am confused is, say this is a Tree[Int]. So the left/right values are nodes, and the value is of type Int.

Why does the type parameter of fold have to be B and not A? I'm confused why there are 2 types A and B and not just type A which is an Int if it is a Tree[Int].

sealed trait Tree[A] {
  def fold[B](node: (B, B) => B, leaf: A => B): B
}
final case class Node[A](left: Tree[A], right: Tree[A]) extends Tree[A] {
  def fold[B](node: (B, B) => B, leaf: A => B): B =
    node(left.fold(node, leaf), right.fold(node, leaf))
}
final case class Leaf[A](value: A) extends Tree[A] {
  def fold[B](node: (B, B) => B, leaf: A => B): B =
    leaf(value)
}

Upvotes: 1

Views: 127

Answers (1)

Frederick Roth
Frederick Roth

Reputation: 2830

Fold is an operation that reduces F[A] to a single value B.

You can of course reduce your tree of Int to a single Int (by adding the integers i.e.) in this case A and B would be the same.

But fold can do much more for you. You can also fold your tree to a String for example to print it's structure.

Fold is simply more general then you expected.

Upvotes: 1

Related Questions