Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

discriminating between many case-classes

 
Bartender
Posts: 4752
184
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi All,

I'm doing an assignment at the moment. I have the following classes:



Now, what I would like to achieve is a mapping of all my Expr classes
to a Set[String]. For each Exp I want to have a Set that gives me all
the Refs from Exp.

For instance:
exp1 = Plus(Ref("A"). Literal(5))

then I would like to have exp1 mapped to the set ("A")

I have this function:



My question is: is there some handy way to get all case classes of the form '_(a,b)' treated in one go,
instead of casing them one by one as I do above? I tried: case _(a,b) => , but that was not allowed.
Neither was:

Greetz,
Piet
 
Ranch Hand
Posts: 121
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Piet

I do not know easy way to do that using your class strucutre (I believe there is no Scala syntax to do that).

However, there is a quite simple solution. I usually do this in the following way


In this case methods could use only structure when they need this. And they could pattern-match with operator type (case BinaryExpr(Plus, _, _)) when they need.
 
Piet Souris
Bartender
Posts: 4752
184
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Maxim, that is an elegant solution.
I guess the instructor didn't want to make it too difficult for us...

Greetz,
Piet
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic