5

I'm looking for a simple CAS system for scala.

It should have the following features:

  • give access to the abstract syntax tree (preferably via case classes for easy matching)
  • parse String to AST
  • simplify expressions

If none exists and I have to write something basic myself, what's the best representation?

I'm thinking something like this:

abstract trait Term
{
  def simplify:Term
  def evaluate(assignment:Var => Double):Double
  def derivative:Term
}

case class Const(c:Int) extends Term
case class Var(x:String) extends Term

case class Negate(x:Term) extends Term
case class Subtract(x:Term, y:Term) extends Term
case class Divide(x:Term, y:Term) extends Term


object Add { def apply(x:Term*):Add = Add(x.toList) }
case class Add(xs : List[Term]) extends Term

object Multiply { def apply(x:Term*):Multiply = Multiply(x.toList) }
case class Multiply(xs:List[Term]) extends Term

case class Power(x:Term, y:Term) extends Term
case class Exp(x:Term) extends Term

I'd implement the simplification algorithm described here, which seems tedious. (But maybe tedium is unavoidable when it comes to simplifying algebraic expressions?)

Some critiques of this specific implementation are:

  • I'll be recursively calling simplify all over the place on the arguments to the case classes (seems like it could be centralized somehow)
  • Dealing with the varargs / List arguments to Add and Mutliply seems like it could get messy
dsg
  • 12,924
  • 21
  • 67
  • 111

1 Answers1

4

I don't know of an existing CAS for Scala.

When doing language processing I normally find it much more pleasant to use pattern matching over a sealed hierarchy rather than OO style polymorphism. Since adding new term types is rare (that means a change of language) and adding new operations common this side of the expression problem seems to fit better.

sealed trait Term
case class Const(c : Double) extends Term
case class Var(x : String) extends Term
case class Negate(x : Term) extends Term
case class Multiply(xs : List[Term]) extends Term
// etc

object CAS {

  // I assume that the assignment map may be incomplete, thus
  // evaluation is really a partial substitution and then simplification
  def evaluate(t : Term, assignment : Var => Option[Double]) : Term = t match {
    case _ : Const => t
    case v : Var => assignment(v) map Const getOrElse v
    case Negate(x) => evaluate(Multiply(Const(-1) :: evaluate(x, assignment) :: Nil), assignment)
    case Multiply(ts) => {
      val evalTs = ts map { t => evaluate(t, assignment) }
      val flattened = evalTs flatMap {
         case Multiply(subs) => subs
         case t => List(t)
      }
      val constTotal = Const((flattened collect { case Const(c) => c }).product)
      val otherTerms = flattened filter { case t : Const => false; case _ => true }
      (constTotal, otherTerms) match {
         case (Const(0), _) => Const(0)
         case (Const(1), Nil) => Const(1)
         case (Const(1), _) => Multiply(otherTerms)
         case _ => Multiply(constTotal +: otherTerms)
      }
    }
    // etc

  }

  private val emptyAssignment : (Var => Option[Double]) = { x : Var => None }

  // simplfication is just evaluation with an empty assignment
  def simplify(t : Term) : Term = evaluate(t, emptyAssignment)
}

One bit of technology I've been meaning to learn about but haven't is attribute grammars. They're supposed to take much of the tedium out of this kind of AST processing. See kiama http://code.google.com/p/kiama/ for a Scala implementation

By the way, while I do use doubles here for your domain you might be better off using a "big rational" - a pair of BigIntegers. They're slow but very precise.

James Iry
  • 19,367
  • 3
  • 64
  • 56
  • Thanks! Any tips about how to simplify expressions of the form: `((a * c * x^2) + (b * x^2))` to be `(a*c + b) * x^2`? The analog was easy to do with `Power`, but the lists for both `Multiply` and `Add` are making it tough for me. – dsg May 19 '11 at 07:13
  • The paper you link to describes a similar transformation from (x^a * y ^ b * x ^ c) into (x ^ (a + c) * y ^ b). The approach they use is simple, after making sure all child nodes of multiplication are the same canonical form, they pop the first item off the list and see if any other nodes have the same base. If so they combine the two. Then they do the same with the remainder. Scala's lists have a handy function called "partition" which will let you split a list according to arbitrary criteria that should let you do just that. – James Iry May 19 '11 at 17:00