Bug 9959 – Add functional pattern matching for object references

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-04-18T09:56:00Z
Last change time
2014-09-16T14:15:14Z
Keywords
pull
Assigned to
nobody
Creator
GenericNPC

Comments

Comment #0 by GenericNPC — 2013-04-18T09:56:20Z
Polymorphism is usually the way to write code that handles objects of different types, bit it is not always possible or desirable. When the code that uses the objects is required to treat objects differently based on class, the D way is using cast&assign inside `if`: if (auto a = cast(A) obj) { ... } else if (auto b = cast(B) obj) { ... } This is not always convenient for two reasons: * You need to write `obj` in every `if` statement. If `obj` is a more complex expression(like the return value of a function) you'll need to store it in an variable beforehand. This is not that cumbersome but still worth mentioning. * An `if` statement is a statement - which means it does not return a value - and creates it's own scope - which means you variables declared in it are not accessible outside. Those two constraints mean that if you need to compute a value differently based on the object's class and use that value after the `if`s, you need to declare the variable before the `if` - and that means you can't make it `const`. My solution is the function `std.algorithm.castSwitch`, which is based on Scala's approach(http://ofps.oreilly.com/titles/9780596155957/RoundingOutTheEssentials.html#MatchingOnType). It is used like this: obj.castSwitch!( (A a) => ..., (B b) => ..., )() It answers both mentioned problems, plus it is more compact readable.
Comment #1 by GenericNPC — 2013-04-18T10:00:51Z
Comment #2 by github-bugzilla — 2014-09-16T14:15:14Z
Commits pushed to master at https://github.com/D-Programming-Language/phobos https://github.com/D-Programming-Language/phobos/commit/cf1aa96bc443eea5a7067d9066a6033c3b424fd8 fix issue 9959 - Add functional pattern matching for object references Add the function std.algorithm.castSwitch, which chooses a delegate based on the class of an object and run that delegate with that object. https://github.com/D-Programming-Language/phobos/commit/575b4aec7f2e901056548dc209f3d15951714c05 Merge pull request #1266 from idanarye/add-functional-pattern-matching-for-object-references fix issue 9959 - Add functional pattern matching for object references