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 toAdd
andMutliply
seems like it could get messy