Class and features

I want to create a special calculator. I think case class is a good idea for operations:

 sealed class Expr case class add(op1:Int, op2:Int) extends Expr case class sub(op1:Int, op2:Int) extends Expr case class mul(op1:Int, op2:Int) extends Expr case class div(op1:Int, op2:Int) extends Expr case class sqrt(op:Int) extends Expr case class neg(op:Int) extends Expr /* ... */ 

Now I can use match-case for parsing. Maybe I should also use traits (i.e.: trait Distributivity , trait Commutativity , etc.), is this possible? Is that a good idea?

+6
scala traits case-class
source share
1 answer

Before you begin to add traits of less clear additional meaning, you must understand the basics correctly. The way you do this makes these classes not very useful, at least not when creating a classic AST (or "parsing tree"). Imagine 4 * (3 + 5). Before you can use the multiplication operation, you must first evaluate the addition. This complicates the situation. What you usually want to get is the ability to write the formula “right away,” for example. Mul (4, Add (3, 5)). However, this will not work because you cannot force Ints or Doubles into your own class hierarchy. The usual solution is a wrapper class for numbers, such as "Num". Then we have: Mul (Num (4), Add (Num (3), Num (5)). This may look complicated, but now you have “all at once” and you can do things like introducing constants and variables, simplification (e.g. Mul (Num (1), x) → x), output ...

To get this you need something along the lines

 sealed trait Expr { def eval:Int } case class Num(n:Int) extends Expr { def eval = n } case class Neg(e: Expr) extends Expr { def eval = - e.eval() } case class Add(e1: Expr, e2: Expr) extends Expr { def eval = e1.eval + e2.eval } ... 

Now you can write a parser that turns "4 * (3 + 5)" into Mul (Num (4), Add (Num (3), Num (5)) and gets the result by calling eval on this expression.

Scala already contains a parsing library called parser combinators. An example close to the code above see http://jim-mcbeath.blogspot.com/2008/09/scala-parser-combinators.html

+13
source share

All Articles