M2 icon indicating copy to clipboard operation
M2 copied to clipboard

`when .. is .. else ..` for top-level switch statements

Open mahrud opened this issue 3 years ago • 5 comments
trafficstars

The d language already has a switch statement. Why doesn't top-level M2 support something similar?

when class x (
    is ZZ do print "integer"
    is QQ do print "rational"
    else print "neither"
    )

Ideally this should also check inheritance, so for instance a MonomialIdeal would pass as an Ideal, or QuotientRing pass as a Ring.

mahrud avatar Dec 08 '21 02:12 mahrud

Dispatching via method functions is probably enough for all practical purposes.

DanGrayson avatar Dec 08 '21 16:12 DanGrayson

Dispatching via method functions is probably enough for all practical purposes.

What? There are lots of uses of switch statements that are not for types! Here is one:

when opts.Strategy (
    is Homogeneous do print "homogeneous strategy"
    is Quotient    do print "quotient strategy"
    else              print "default strategy"
    )

or many many other uses of switch statements out there in other languages.

Conveniently, there's a section for advantages of switch statements on wikipedia. Among them:

  • Easier to debug
  • Easier for a person to read
  • Easier to understand, and consequently easier to maintain
  • Easier to verify that all values are handled

mahrud avatar Dec 08 '21 21:12 mahrud

Well, you mentioned inheritance in your original post, and invoked the "when" statement in the D language, so I inferred you intended this to be used for type dispatch.

DanGrayson avatar Dec 13 '21 20:12 DanGrayson

Ah, I see. No I meant a general switch statement. I'm curious how a new, complex feature would be added to the syntax.

mahrud avatar Dec 13 '21 22:12 mahrud

To add it to the syntax, you would have to add the new keywords with suitable parsing precedence, add an item to the union type "Code", and add an item to the union type "ParseTree". Take a look at "ifCode" and "IfThenElse" and do something similar.

DanGrayson avatar Dec 14 '21 18:12 DanGrayson