Type unions in D
Jeremie Pelletier
jeremiep at gmail.com
Tue Sep 15 16:44:02 PDT 2009
Justin Johansson Wrote:
> What's the best way of emulating a system of quantified type unions in D (D1)?
>
> By type unions (sometimes called algebraic sums in the literature), I don't mean the C/C++ "union" facility.
>
> Suppose there is some class X, I'd like to have a first class type for representing the following quantified types (using RegExp notation):
> X? zero or one instances of an X (call this type XQ)
> X a single instance of X
> X* zero or more instances of X (call this type XS)
> X+ at least one X (call this type XP)
>
> To unify the whole thing, now let X, XQ, XS and XP all be derived from a common base type T.
>
> Note that Scala has the Option, Some and None classes which kind of handles (but not exactly) the XQ case.
>
> Brendan Eich, JavaScript inventor, apparently has suggested type unions for that language. Some FP languages also have type systems that support type unions.
>
> http://wiki.ecmascript.org/doku.php?id=meetings:minutes_oct_13_2005
>
> "Type Unions
> Brendan thinks we should have some ability for type unions in the language.
>
> var x : Number | Null
>
> It would be good to have something like this because otherwise developers end up enforcing their invariants on their own, with the potential for buggy code."
>
> As always, thanks for all replies.
>
> Justin Johansson
>
What you want sounds a lot like a variant type. Check std.variant in phobos, it has a template to let you define custom variants through type tuples.
More information about the Digitalmars-d
mailing list