ALGOL68-like union type switches?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Fri Apr 6 18:47:17 PDT 2007


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



More information about the Digitalmars-d mailing list