Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing case class to display Expressions
    primarykey
    data
    text
    <p>I am trying to achieve the example shown in Martin Odersky's CourseRa Scala course to try and display expressions holding Sums/Prods using appropriate brackets. I came up with the below solution:</p> <pre><code>package expressions trait Expr { def eval : Int = { this match { case Number(n) =&gt; n case Sum(e1,e2) =&gt; e1.eval + e2.eval } } //def show( exp : Expr) : String } case class Number(n:Int) extends Expr case class Sum(e1: Expr, e2: Expr) extends Expr case class Prod(e1 : Expr, e2 : Expr) extends Expr case class Var(x:Char) extends Expr object testExpr { def show(exp : Expr) : String = { exp match { case Number(x) =&gt; x.toString() case Sum(e1, e2) =&gt; show(e1) + "+" + show(e2) case Prod(e1,e2) =&gt; val st1 = e1 match { case Sum(a,b) =&gt; "(" + show(Sum(a,b)) + ")" case _ =&gt; show(e1) } val st2 = e2 match { case Sum(a,b) =&gt; "(" + show(Sum(a,b)) + ")" case _ =&gt; show(e2) } st1 + "*" + st2 case Var(x) =&gt; x.toString } } } object test extends App{ println(testExpr.show(Sum(Number(1),Number(2)))) println(Sum(Number(1),Number(3)).eval) println(testExpr.show(Sum(Number(2),Prod(Number(10),Var('x'))))) println(testExpr.show(Sum(Prod(Number(2),Var('x')),Var('y')))) println(testExpr.show(Prod(Sum(Number(2),Var('x')),Var('y')))) println(testExpr.show(Prod(Sum(Number(2),Var('x')),Sum(Number(3),Var('y'))))) } </code></pre> <p>The way I am deciding on putting the brackets is definitely not the best solution. Can anyone suggest a better solution to achieve the same.</p> <p>Thanks and Regards, Paromita</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload