How to define this class in scala
data NestedList a = Elem a | List [NestedList a]
This in Haskell means a NestedList is a Type which can contain either Elem or another NestedList. Is it possible to do these kind of recursive definitions in scala?
Actually this is what I am trying to acheive
Check Problem 7 here in this page.
Updated….
Follwing the answers below, I created the NestedList Trait and case classes for Elem and NList.
Trying to implement the flatten, I am stuck here..
def flatten[T](xs: NestedList[T]): List[T] = xs match{
case Elem(xs) => List(xs)
//case NList //have to fill this case
}
Algebraic Data Types from Haskell are idiomatically translated into sealed class hierarchies in Scala.
For example:
UPDATE
Thomas’s answer shows the recursive type definition nicely. However, it is interesting that you can’t make
NLista case class — a type error is reported for the synthesised methodsameElements, which is used inequals. This sounds similar to: https://lampsvn.epfl.ch/trac/scala/ticket/2867It works is the repeated parameters are replaced with
Seq: