Self-referential tuples?

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 9 17:07:17 PDT 2015


On 06/10/2015 01:48 AM, Timon Gehr wrote:
> On 06/10/2015 01:04 AM, Andrei Alexandrescu wrote:
>> On 6/9/15 3:58 PM, Timon Gehr wrote:
>>> On 06/09/2015 05:28 PM, Andrei Alexandrescu wrote:
>>>> Following the use of This in Algebraic
>>>> (https://github.com/D-Programming-Language/phobos/pull/3394), we can
>>>> apply the same idea to Tuple, thus allowing one to create
>>>> self-referential types with ease.
>>>>
>>>> Consider:
>>>>
>>>> // A singly-linked list is payload + pointer to list
>>>> alias List(T) = Tuple!(T, This*);
>>>>
>>>> // A binary tree is payload + two children
>>>> alias Tree(T) = Tuple!(T, This*, This*);
>>>> // or
>>>> alias Tree(T) = Tuple!(T, "payload", This*, "left", This*, "right");
>>>>
>>>> // A binary tree with payload only in leaves
>>>> alias Tree2(T) = Algebraic!(T, Tuple!(This*, This*));
>>>>
>>>> Is there interest in this? Other application ideas to motivate the
>>>> addition?
>>>>
>>>>
>>>> Andrei
>>>
>>> Well, the issue is with this kind of use case:
>>>
>>> alias List(T)=Algebraic!(Tuple!(),Tuple!(T,This*));
>>
>> So a list is either nothing, or a head and a tail. What is the problem
>> here? -- Andrei
>
> It's about which type 'This' refers to. Is it the Algebraic or the
> Tuple? I assume here it would be the algebraic, which is expected, but
> it can get non-obvious quickly especially when e.g. a template parameter
> is a recursive tuple and the template uses the type in an Algebraic.
> It's just a mess. E.g. what happens if you do List!(Tree!int)?
> ReplaceType would need to treat Tuples specially, and then you lose the
> other semantics even though it might sometimes be needed. 'This' is a
> cute hack, but it doesn't replace a proper template fixpoint operator.

If I'm not mistaken Algebraic already suffers from this kind of "This 
replacement hijacking".

alias List(T)=Algebraic!(Tuple!(),Tuple!(T,std.variant.This*));

List!(List!(int)) // not a list of list of int, is it?





More information about the Digitalmars-d mailing list