scala - Instantiating Case Class with Trait -
how can instantiate tree per below trait , case classes?
sealed trait tree[+a] case class leaf[a](value: a) extends tree[a] case class branch[a](left: tree[a], right: tree[a]) extends tree[a]
source: functional programming in scala
example: how code following tree of type string
?
"top" / \ "middle-left" "middle-right" / \ "bottom-left" "bottom-right"
with class hierarchy have given wouldn't able create resembling example tree want, because branch can accept left , right sub-trees, not value (the text "top").
if want branch nodes have value, modify class hierarchy follows:
sealed trait tree[+a] case class leaf[a](value: a) extends tree[a] case class branch[a](value: a, left: option[tree[a]] = none, right: option[tree[a]] = none) extends tree[a]
note option-al nature of sub-trees, default of none, allowing missing left or right sub-trees without resorting nulls.
your example tree generated follows:
val tree = branch("top", some(branch("middle-left", some(leaf("bottom-left")))), some(branch("middle-right", right = some(leaf("bottom-right")))))
Comments
Post a Comment