Examples of classes and template matching in a list

What I would like to do is simplify this expression

Opt (Opt (ExpList (List ( Opt (Opt (Var ("option")))))))

to get something like this

Opt (ExpList (List ( Opt (Var ("option")))))


What will match the expression seems to simplify all the expressions inside the list.

What are the best practices for such tasks?

Missed code snippet:

object CaseClassPatternMatching extends App { abstract class Expr case class Var(name: String) extends Expr case class Opt(expr: Expr) extends Expr case class ExpList(listExp: List[Expr]) extends Expr def joinOpt(feature: Expr): Expr = feature match { case Opt(Opt(f)) => joinOpt(Opt(f)) // Opt(Opt("test")) --> Opt("test") // case ExpList(list) => ???? // What to do there? case _ => feature } val expr1: Expr = joinOpt(Opt(Opt(Opt(Var("optional"))))) println(Opt(Var("optional"))) // Output: Opt(Var(optional)) --> That one is OK... val expr2: Expr = joinOpt(Opt(Opt(ExpList(List(Opt(Opt(Var("optional")))))))) println(expr2) // Output: Opt(ExpList(List(Opt(Opt(Var(optional)))))) --> Not OK... // How to simplify expressions inside list? } 

[EDIT]

For those who are interested in you, a similar topic:

Scala case classes, pattern matching and varargs

+4
source share
2 answers

You need four cases:

 def joinOpt(feature: Expr): Expr = feature match { // remove extra Opt // (you can use @ to avoid recreating Opt) case Opt(opt @ Opt(_)) => joinOpt(opt) // preserve single Opt case Opt(expr) => Opt(joinOpt(expr)) // apply function to all elements in inner list case ExpList(list) => ExpList(list map joinOpt) case _ => feature } 
+7
source

Well, I would write joinOpt as follows:

 def joinOpt(feature: Expr): Expr = feature match { case Opt(Opt(f)) => joinOpt(Opt(f)) // Opt(Opt("test")) --> Opt("test") case ExpList(list) => ExpList(list map joinOpt) case other => other } 
+3
source

Source: https://habr.com/ru/post/1395328/


All Articles