Spec#, nullables and more

retard re at tard.com.invalid
Sat Nov 6 05:30:03 PDT 2010


Sat, 06 Nov 2010 13:18:34 +0100, Lutger wrote:

> retard wrote:
> 
>> Sat, 06 Nov 2010 10:20:24 +0100, Simen kjaeraas wrote:
>> 
>>> Walter Bright <newshound2 at digitalmars.com> wrote:
>>> 
>>>> Consider non-nullable type T:
>>>>
>>>>    T[] a = new T[4];
>>> 
>>> As others have pointed out, this would be impossible for a proper
>>> non-nullable type. The only ways to create an array of non-nullable
>>> elements would be a literal, concatenation with non-nullable elements,
>>> or casting an existing array of nullable elements.
>> 
>> That's bs.. the functional way to doing this is to wrap all elements in
>> a Maybe monad. It makes the "null check" explicit.
> 
> Isn't a list of Maybe T a functional way to express the nullable side
> effect, rather than express non-nullable types? After all, it is typed
> as Maybe T, not T. There is a code path for nil in the monadic case
> right, but not for nullable types. Or do I completely miss the point?

Right, the type 'T' expresses the basic case where you don't have any 
null/nil values - the non-nullable case. Everything must be initialized 
with a proper value (lazy initialization is possible, though). The type 
'Maybe T' adds the special null case. In D when a function receives a 
nullable argument, you must do:

class Car { void start() {} }

void start_the_car(Car c) {
  if (c != null)
    c.start();
  else
    throw new Error("The car wasn't initialized!");
}

In a functional language:

start_the_car c = case c of
  Just car -> start car
  Nothing -> error "not initialized"

----

With non-nullable types:

class Car { void start() {} }

void start_the_car(Car# c) {
  c.start();
}

In a functional language:

start_the_car = start


More information about the Digitalmars-d mailing list