Self-referential tuples?
Brian Rogoff via Digitalmars-d
digitalmars-d at puremagic.com
Wed Jun 10 08:52:58 PDT 2015
On Tuesday, 9 June 2015 at 23:48:05 UTC, Timon Gehr wrote:
> 'This' is a cute hack, but it doesn't replace a proper template
> fixpoint operator.
Could you explain this a bit more, maybe using some pseudo-D for
your proposed template fixpoint operator? Thanks.
I don't think I'd need such a thing for the JSON AST example,
since it isn't parameterized by type. There, the D mapping looks
clumsy because, as Andrei noticed, the 'fields' are not named. If
you map the OCaml straight to D you get something like what I
write below, and you want both the Kind and the internal
structure to be non-private so you can write functions which work
on them. It's the same as tagged unions/variants in other
languages but so much easier to use.
enum Kind {
Bool,
Number,
String,
Null,
Array,
Object
}
alias JSON = JSONStruct *;
struct JSONStruct {
public:
Kind kind;
union {
bool jsonBool;
double jsonNumber;
string jsonString;
JSON[] jsonArray;
JSON[string] jsonObject;
}
this(Kind kind, bool jsonBool)
in { assert(kind == Kind.Bool); }
body {
kind = Kind.Bool;
this.jsonBool = jsonBool;
}
this(Kind kind, double jsonNumber)
in { assert(kind == Kind.Number); }
body {
kind = Kind.Number;
this.jsonNumber = jsonNumber;
}
this(Kind kind, string jsonString)
in { assert(kind == Kind.String); }
body {
kind = Kind.String;
this.jsonString = jsonString;
}
this(Kind kind)
in { assert(kind == Kind.Null); }
body {
kind = Kind.Null;
}
this(Kind kind, JSON[] jsonArray)
in { assert(kind == Kind.Array); }
body {
kind = Kind.Array;
this.jsonArray = jsonArray;
}
this(Kind kind, JSON[string] jsonObject)
in { assert(kind == Kind.Object); }
body {
kind = Kind.Object;
this.jsonObject = jsonObject;
}
}
More information about the Digitalmars-d
mailing list