Hi all, I just started learning Scala and FP through Essential-Scala ebook that is open source by underscore.io. I’m currently learning about generic, functions and fold method. I stumble upon a question to code
"A Tree of type A is a Node with left and right Tree or a Leaf with an element of type A. Implement this algebraic data type along with a fold method."
My answer for the fold method was totally wrong, I put the type to be A for everything (i.e. no type B written at all) because i thought if tree is of type A then the nodes and leafs will also be type A as well.
The code shown below is the correct answer and i had a hard time understanding (i.e. how does type B come about) and how to decide when to declare different type (i.e. A,B,C, …etc). Any help would be appreciated, thank you.
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)
}