Simplify expression in Scala -
i have such case classes:
abstract class tree case class sum(l: tree, r: tree) extends tree case class var(n: string) extends tree case class const(v: int) extends tree now write such object :
object main { type environment = string => int def derive(t: tree, v: string): tree = t match { case sum(l, r) => sum(derive(l, v), derive(r, v)) case var(n) if (v == n) => const(1) case _ => const(0) } def eval(t: tree, env: environment): int = t match { case sum(l, r) => eval(l, env) + eval(r, env) case var(n) => env(n) case const(v) => v } def simple(t: tree): const = t match { case sum(l, r) if (l.isinstanceof[const] && r.isinstanceof[const]) => const(l.asinstanceof[const].v + r.asinstanceof[const].v) case sum(l, r) if (l.isinstanceof[sum] && r.isinstanceof[sum]) => const(simple(l).v+ simple(r).v) case sum(l, r) if (l.isinstanceof[sum]) => const(simple(l).v + r.asinstanceof[const].v) case sum(l, r) if (r.isinstanceof[sum]) => const(simple(r).v + l.asinstanceof[const].v) } def main(args: array[string]) { val exp: tree = sum(sum(var("x"), var("x")), sum(const(7), var("y"))) val env: environment = { case "x" => 5 case "y" => 7 } println("expression: " + exp) println("evaluation x=5, y=7: " + eval(exp, env)) println("derivative relative x:\n " + derive(exp, "x")) println("derivative relative y:\n " + derive(exp, "y")) println("simplified expression:\n" + simple(derive(exp, "x"))) } } i new in scala. possible write method simple small count of code , maybe in scala way?
thanks advice.
you're there. in scala, extractors can nested:
def simple(t: tree): const = t match { case sum(const(v1), const(v2)) => const(v1 + v2) case sum(s1 @ sum(_,_), s2 @ sum(_, _)) => const(simple(s1).v+ simple(s2).v) case sum(s @ sum(_, _), const(v)) => const(simple(s).v + v) case sum(const(v), s @ sum(_, _)) => const(simple(s).v + v) } of course, give warnings incomplete matches, , sx @ sum(_, _) repeatedly suggests there may better approach includes matching on const , var @ root level , making more recursive calls simple.
Comments
Post a Comment