Pattern matching is written using tree MATCH(CASE(...), ...)
:
scala> import treehugger.forest._, definitions._, treehuggerDSL._
import treehugger.forest._
import definitions._
import treehuggerDSL._
scala> val tree = (DEF("maxList", "A")
withTypeParams(TYPEVAR("T") VIEWBOUNDS TYPE_ORDERED("A"))
withParams(PARAM("elements", TYPE_LIST("A")))) :=
REF("elements") MATCH (
CASE(ListClass UNAPPLY()) ==>
THROW(IllegalArgumentExceptionClass, "empty list!"),
CASE(ListClass UNAPPLY(ID("x"))) ==> REF("x"),
CASE(ID("x") UNLIST_:: ID("rest")) ==> BLOCK(
VAL("maxRest") := REF("maxList") APPLY(REF("rest")),
IF(REF("x") INT_> REF("maxRest")) THEN REF("x")
ELSE REF("maxRest")
)
)
[1m[34mtree[0m: [1m[32mtreehugger.forest.DefDef[0m = DefDef(Modifiers(, , Map()),maxList,List(TypeDef(Modifiers(, , Map()),T,List(),TypeTree())),List(List(ValDef(Modifiers(<param>, , Map()),Typed(Ident(elements),TypeTree()),EmptyTree))),TypeTree(),Match(Ident(elements),List(CaseDef(UnApply(Ident(List),List()),EmptyTree,Throw(Apply(Select(New(TypeTree()),<init>),List(Literal(Constant(empty list!)))))), CaseDef(UnApply(Ident(List),List(Ident(x))),EmptyTree,Ident(x)), CaseDef(InfixUnApply(Ident(x),$colon$colon,List(Ident(rest))),EmptyTree,Block(List(ValDef(Modifiers(, , Map()),Ident(maxRest),Apply(Ident(maxList),List(Ident(rest))))),If(Infix(Ident(x),>,List(Ident(maxRest))),Ident(x),Ident(maxRest)))))))
scala> treeToString(tree)
[1m[34mres0[0m: [1m[32mString[0m =
def maxList[T <% Ordered[A]](elements: List[A]): A =
elements match {
case List() => throw new IllegalArgumentException("empty list!")
case List(x) => x
case x :: rest => {
val maxRest = maxList(rest)
if (x > maxRest) x
else maxRest
}
}