Type unions in D

Ary Borenszweig ary at esperanto.org.ar
Wed Sep 16 05:07:15 PDT 2009


Justin Johansson escribió:
> bearophile Wrote:
> 
>> Justin Johansson:
>>> What's the best way of emulating a system of quantified type unions in D  (D1)?
>> Having nullable values may be useful, having nonnull class references can probably be very useful, having tagged unions (I am talking as C unions here) can be useful. But can you show me some usercases/purposes for what you are asking for? I think other people too here are curious.
> 
> Thanks for asking.  Here's a use case.  Suppose you have a container class which represents a list of numbers.  Let's call this class ListOfNums. Now a ListOfNums can contain zero or more numbers.  Now you want a function called max that takes a ListOfNums, xs, as an argument and returns the number in the list, xs, that is greater than or equal to all other numbers in xs.
> 
> So if xs contains (3, 9, 9, 2), max( xs) returns 9.
> 
> Now it makes sense that xs should contain at least one number, so if xs contains just (3), max( xs) returns 3.
> 
> 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?
> 
> Put another way, what is the maximum number in an empty list of numbers?

So after invoking max on the list you would want to know whether it 
contains a single element or it's the empty list, right? If so, why not 
asking it before invoking the max function?

if (xs.isEmpty) {
   // no max, do something
} else {
   auto max = max(xs);
   // do something *else*
}

I've seen this code a lot of times, and it being:

auto max = max(xs);
if (max.isEmpty) {
   // no max, do something
} else {
   // do something *else*
}

is exactly the same thing, unless you are planning to do something with 
the list that contains max.

At least one of the first things I learned when studying computer 
science if function pre and postconditions, and max's is "list is not 
empty". :)

What's wrong with that?



More information about the Digitalmars-d mailing list