Self-referential tuples?

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 9 10:17:28 PDT 2015


On 6/9/15 8:59 AM, Brian Rogoff wrote:
> On Tuesday, 9 June 2015 at 15:28:16 UTC, 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?
>
> Yes, I'm interested. As a practical example, how would you represent a
> JSON AST type, which might look something like this in OCaml (type json
> at the top)
>
>    http://mjambon.com/yojson-doc/Yojson.Safe.html
>
> using Algebraic? And once you've encoded it using Algebraic, how do you
> operate on it, for example, how would you write a 'toString' on the AST?
> These are both straightforward in OCaml (the straightforward yet
> inefficient toString pracitically writes itself from the definition, the
> efficient version with buffers is only a little more involved) so a D
> version would be a good test.

Excellent example! Here's a shot:

alias JsonPayload = Algebraic!(
     bool,
     double,
     long,
     string,
     This[],
     This[string]
);

I notice that in Ocaml you get to give names to fields, so I added 
https://issues.dlang.org/show_bug.cgi?id=14670 to investigate the matter.

Converting a complex JsonPayload to string can be done with relative 
ease by using visitation.


Thansk,

Andrei



More information about the Digitalmars-d mailing list