ALGOL68-like union type switches?

Peter Modzelewski peter.modzelewski at gmail.com
Fri Apr 6 19:19:19 PDT 2007


Chris Nicholson-Sauls napisa?(a):
> Something which randomly occurred to me as a nice thing to have, if only 
> there is a clean way to manage it.  In ALGOL-68 one can do something 
> like this:
> 
> # mode node = union (real, int, string);
> #
> # node n := "1234";
> #
> # case n in
> #   (real r):   printf(($"real: ", d.3d$, r)),
> #   (int i):    print(("int: ", i)),
> #   (string s): print(("string: ", s))
> #   out         print(("?: ", n))
> # esac
> 
> Which will output the node 'n' differently depending on the type of its 
> currently bound data.  So how do we do this in D?  Right now, its 
> typically emulated with something like:
> 
> # struct Node {
> #   static enum : uint { REAL, INT, STR }
> #
> #   uint type ;
> #
> #   union {
> #     double r ;
> #     long   i ;
> #     char[] s ;
> #   }
> # }
> #
> # Node n = {s : "1234"} ;
> #
> # switch (n.type) {
> #   case Node.REAL : writefln("real: %.3s"    , n.r); break;
> #   case Node.INT  : writefln("int: "         , n.i); break;
> #   case Node.STR  : writefln("string: \"%s\"", n.s); break;
> #
> #   default:
> #     writefln("?: %X-%X", n.type, n.i);
> # }
> 
> So close.  Not sure what can be done about it, though.
> 
> -- Chris Nicholson-Sauls

this is also RPC meening of unions iirc , union itself and variable to 
hold it's type. Something simular also appears in pascal as far as i know.

the truth is that you don't always need to know the type. simplest 
example is union made to easy color menagment

union {
	ubyte[4] rgba;
	uint intcolor;
}

so you can put into it a rbga color what is quite easy, and with no cost 
get it's int equivalent

type recognicion of unions would always need to use additional variable 
beeing a switch for what type is actually held in a union, no matter if 
it is build in language or decided by programmer.

In my opinion building that into language is not a necesserity... the 
decission should be left in coders hands.

Peter



More information about the Digitalmars-d mailing list