Branbron
Branbron

Reputation: 101

Simplifying Simple Expressions in Scala

I am learning scala and attempted to create a method that will simplify a simple expression by applying simple arrhythmic rules. However it seems to not be changing the expression they way I like, or at all for the matter. The simplification doesn't show when I print it out. I would appreciate any help/advice, thanks! The print statements I use to test are below followed by the output.

println("Expression: " + exp)
println("Simplified: " + simplify(exp))

Output:

Expression: ((1*x)+(0+y)) <--This is correct

Simplified: ((1*x)+(0+y)) <--This is not what I expect. I expected something like ((x)+(y))

My code follows:

    lazy val exp: Tree = Sum(Times(Const(1), Var("x")), Sum(Const(0), Var("y")))

    abstract class Tree
    case class Sum(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "+" + r + ")"
    }
    case class Minus(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "-" + r + ")"
    }
    case class Times(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "*" + r + ")"
    }
    case class Divide(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "/" + r + ")"
    }
    case class Var(n: String) extends Tree {
      override def toString = n
    }
    case class Const(v: Int) extends Tree {
      override def toString = v.toString
    }

    def simplify(t: Tree): Tree = t match {
      case Times(Const(1), r)     => simplify(r)
      case Times(l, Const(1))     => simplify(l)
      case Times(Const(0), r)     => Const(0)
      case Times(l, Const(0))     => Const(0)
      case Sum(Const(0), r)       => simplify(r)
      case Sum(l, Const(0))       => simplify(l)
      case Minus(l, Const(0))     => simplify(l)
      case Minus(l, r) if l == r  => Const(0)
      case Divide(Const(0), r)    => Const(0)
      case Divide(l, Const(1))    => simplify(l)
      case Divide(l, r) if l == r => Const(1)
      case _                      => t
    }

Upvotes: 1

Views: 816

Answers (1)

user1804599
user1804599

Reputation:

You didn't handle these cases:

case Times(l, r) => Times(simplify(l), simplify(r))
case Sum(l, r) => Sum(simplify(l), simplify(r))
case Minus(l, r) => Minus(simplify(l), simplify(r))
case Divide(l, r) => Divide(simplify(l), simplify(r))

Also, you probably want to write a wrapper that that keeps simplifying until it cannot be simplified anymore (i.e. until simplify(x) == x).

Upvotes: 4

Related Questions