M2
M2 copied to clipboard
`when .. is .. else ..` for top-level switch statements
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.
Dispatching via method functions is probably enough for all practical purposes.
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
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.
Ah, I see. No I meant a general switch statement. I'm curious how a new, complex feature would be added to the syntax.
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.