Improvement to switch-case statement

Yigal Chripun yigal100 at gmail.com
Sat Jan 3 04:49:10 PST 2009


Benji Smith wrote:
> Yigal Chripun wrote:
>> Maybe it's just me but all those C-style statements seem so arcane and
>> unnessaccary. real OOP languages do not need control structures to be
>> part of the language - they're part of the class library instead.
>> Here's some Smalltalk examples: (and D-like comparable code)
>
> Interesting...
>
> Assuming the core language had no control structures, how would library
> authors implement them?
>
> If the language itself lacked IF, ELSE, SWITCH, CASE, DO, WHILE, FOR,
> and presumably GOTO... how exactly would you go about implementing them
> in a library?
>
> --benji

Simple. using polymorphism and closures (called blocks in Smalltalk).

for example, Here's a simple D implementation for "if", "else":

abstract class Boolean {
   void IfTrue(void delegate() dg);
   void IfFalse(void delegate() dg);
   void IF_ELSE(void delegate() dgTrue, void delegate() dgFalse) {
     IfTrue(dgTrue);
     IfFalse(dgFalse);
   }
  ...
}

class True : Boolean {
   void IfTrue(void delegate() dg) {
     dg();
   }
   void IfFalse(void delegate() dg) { /* nothing to do here */ }
}

// class False is implemented similarly

you use it like this:
(a > 4).IF_ELSE(dg1, dg2);

if (a > 4) is "true" it'll be of the type True (in Smalltalk everything 
is an object, btw) therefore the methods of True will be called - IfTrue 
will evaluate the delegate, and IfFalse will do nothing.



More information about the Digitalmars-d mailing list