digitalmars.D - Custom Type Unions
- Dhruv Singal (25/25) May 26 2019 I'm trying to implement an interpreter in D as a class project.
- Dennis (9/13) May 26 2019 Structs and unions can be returned in D. You can implement a
I'm trying to implement an interpreter in D as a class project.
Having already written the the parser and interpreter in Racket,
I'm having trouble figuring out if dlang has a way for me to
create a union object that can be one of many object and have it
be a first-class object, ie it can be the return type of
functions. Is this something dlang supports? If not, is there a
better way of implementing this?
Below is some rudimentary code I wrote to test this:
import std.stdio;
import std.string;
alias string = immutable(char)[];
union Value {real realV; bool booV; string stringV; primV prim;};
struct primV{
real function(int, int) doer;
}
real add (int a, int b){
real sum = a+b;
return cast(real)sum;
}
void main(){
writeln("Beginning Interp");
primV adder = primV(&add);
real x = adder.doer(5,6);
writeln(x);
}
May 26 2019
On Sunday, 26 May 2019 at 17:59:21 UTC, Dhruv Singal wrote:I'm having trouble figuring out if dlang has a way for me to create a union object that can be one of many object and have it be a first-class object, ie it can be the return type of functions. Is this something dlang supports?Structs and unions can be returned in D. You can implement a tagged union [1] yourself with them, or use an existing library solution. The standard library has std.variant [2], but I'd recommend the sumtype package [3] (see the 'Features' section in the package description). [1] https://en.wikipedia.org/wiki/Tagged_union [2] https://dlang.org/phobos/std_variant.html [3] http://code.dlang.org/packages/sumtype
May 26 2019








Dennis <dkorpel gmail.com>