Type unions in D

bearophile bearophileHUGS at lycos.com
Thu Sep 17 05:14:14 PDT 2009


Justin Johansson:

>But what if xs contains no numbers i.e. xs = (), the empty list?  What should max( xs) return in the way of a meaningful result short of throwing an exception?<

In both Python and my dlibs it throws an exception.


>An elegant solution to this problem is to specify the max function as taking a quantified list of zero or more numbers and returning another quantified list of numbers which may contain either zero numbers or just one number: zero numbers if the argument list is empty and a single number (being the maximum number in the argument list) if the argument number list is non-empty.<

Cute.


>The important point in this solution is realizing a type system that treats a list of zero_or_one numbers, a list of zero numbers, a list of zero_or_more numbers, etc, as distinct types.<

I don't understand the correlation from this last part and what you have written about max().

Maybe what can be useful is to define as a type a "not empty iterable", so if max() takes as input such type it's sure to not throw an exception. In general iterables can be lazy, their items can be computed on the fly, so there's no way to know at compile time if an iterable will be empty or not.

Bye,
bearophile



More information about the Digitalmars-d mailing list