In Scala, I’d like to be able to define a generic type of abstract syntax tree nodes sort of like this
sealed abstract class AST[T <: AST[T]] {
def child : List[T] ;
}
case class LeafAST[T <: AST[T]]( x : Int ) extends AST[T] {
def child = Nil
}
case class BranchAST[T <: AST[T]]( left : T, right : T ) extends AST[T] {
def child = left :: right :: Nil
}
Now I can write generic code like this
def countLeaves[T <: AST[T]]( x : AST[T]) : Int = x match {
case LeafAST( x ) => 1
case BranchAST( left, right ) => countLeaves[T](left) + countLeaves[T](right)
}
Now my first problem is that the keyword sealed seems to have no effect. If I omit a case from the match expression, there is no error. Why and how can I write what I want? (I have other problems –e.g. how to specialize AST–, but I’ll just stick to one problem per post.)
There is no error — there is a warning. For example:
You can turn it into an error with the flag
-Xfatal-warnings.