Suppose you run the following programs:
sealed trace Expr
case class N(n:Int)extends Expr
case class Var(x:String, a:Int, n:Int)extendsExpr
case class Add (n:Expr*) extensions Expr
case class Mul(n:Expr*) extensions Expr
default(xs:List [Expr]):Expr=xs match{
caseList()=>N(0)
caseList(xs) =>xs
case xs=>Add(xs:_*)//Add(List(N(N(1),N(2),Var(x,2,2))))
}
println(add(List(N(1), N(2), Var("x", 2, 2))))//Add(List(N(1), N(2), Var(x, 2, 2))))
Expected output for this program is
Add(N(1),N(2),Var(x,2,2)))
However, the actual output is
Add (List(N(1), N(2), Var(x, 2, 2))))
That's what happens.Could you tell me how to achieve the desired output for the above program?
I look forward to your kind cooperation.
scala
Override toString to fiddle with the output.
Is it like this?
sealed trace Expr
case class N(n:Int)extends Expr
case class Var(x:String, a:Int, n:Int)extendsExpr
case classAdd(n:Expr*)extendsExpr{
override def to String(): String="Add("+n.mkString(",")+")"
}
case class Mul(n:Expr*) extensions Expr
object Main {
default(xs:Seq[Expr]):Expr=xs match{
case Seq() = > N(0)
case Seq(xs) = > xs
case xs=>Add(xs:_*)
}
defmain(args:Array [String]) {
println(add(List(N(1),N(2),Var("x",2,2))))
}
}
Note: The question seems to be "I want the output to be Add(N(1), N(2), Var(x,2,2))
" rather than "I want the constructor Add(n:Expr*)
to take variable length arguments but store them in the field of the Add class."In conclusion, scala would be impossible in principle, just as the number of fields in the Java class does not change dynamically.
Even if the constructor takes the variable length argument Add(n:Expr*)
in scala, it is actually just a class with a single field n
where Add(n:Expr*)
changes the way the arguments are passed.
© 2024 OneMinuteCode. All rights reserved.