Is the other-kind-of-null really necessary in Nullable and Variant?
Idan Arye
GenericNPC at gmail.com
Mon Apr 29 13:00:30 PDT 2013
On Monday, 29 April 2013 at 18:20:35 UTC, Simen Kjaeraas wrote:
> On 2013-04-29, 19:57, Idan Arye wrote:
>
> Now, consider the fact we have Nullable in Phobos.
Yes, we have `Nullable` in Phobos. It works by having two member
fields - `_value`, which stores the value, and `_isNull`, which
specifies if the `Nullable` is null or not. Let's implement a
bare bones Linked List:
class Node(T){
T value;
Nullable!(Node!T) next;
this(){}
this(T value){
this.value=value;
}
this(T value,Node!T next){
this.value=value;
this.next=next;
}
}
Now lets create an instance:
auto myList=new Node("Hello");
What will happen?
We create a new `Node!string`. it's `value` will be set to
"hello", and since the one-argument constructor does not modify
`next`, it will it will remain as the init value of
`Nullable!(Node!string)`. What is the init value of
`Nullable!(Node!string)`?
The init value of `Nullable!(Node!string)` is an object with two
member fields - `value` of type `string` and `next` of type
`Nullable!(Node!string)`. The default constructor modifies
neither, so they will both remain with their initial values. The
init value of `string` is an empty string. What is the init value
of `Nullable!(Node!string)`? To find the answer, return to the
beginning of this paragraph and read it again.
You are not supposed to be reading this paragraph. You are
supposed to be stuck in an infinite recursion in the previous
paragraph. As a human, you can cheat and escape it, but the
computer is not so lucky - it'll allocate more and more objects
until it'll crash with a stack overflow.
Actually - that won't happen, since the compiler is smart enough
to detect type recursion and emit e compile time error. But the
problem remains - we are left unable to implement any type of
recursive structure.
More information about the Digitalmars-d
mailing list