Type unions in D

Jeremie Pelletier jeremiep at gmail.com
Tue Sep 15 20:43:24 PDT 2009


Justin Johansson Wrote:

> Jeremie Pelletier Wrote:
> 
> > As for the max of an empty set, you can just return zero.
> 
> Well you could return -1, 99 or any arbitrary integer for that matter; just that it doesn't make sense to do that from a pure maths perspective.  Mathematicians have spent centuries trying to make number systems consistent.  The invention (or discovery**) of "i", the square-root of minus-one, was a major major break-through.  In similar vein, it's nice if the type systems we use for programming follow from a consistent set of axioms. ;-)
> 
> (**Is mathematics invention or discovery?)
> 
> <JJ/>
> 

The line between invention and discovery is rather thin, I myself like to think of both as two sides of a same coin. For inventions you need to first discover how to do it, and for discoveries you need to invent the system to describe it.

Basically anything that draws a line between how we perceive something and how we communicate it can be thought of in terms of semantics and syntax respectively. You discover the semantics and then invent the syntax to describe it, so other people can study your syntax and hopefully get a grasp of the semantics you originally had in mind.

As for your code, you could always use more template parameters to control the behavior of your list type:

class ListOfNums(T, T DefaultValue = T.init, bool ThrowOnEmpty = false)
    if(isNumeric!T)
{
    T max() const {
        static if(ThrowOnEmpty)
            if(!nums.length) throw new EmptyListOfNumsException();

        T max = Defaultvalue;
        foreach(n; _nums) if(n > max) max = n;
        return max;
    }
    T[] _nums;
}




More information about the Digitalmars-d mailing list