Re:Implementing a programming language in D: Lexical Analysis
by jeremiep on Monday December 28, 2015 @05:07PM
(#10803681)
There's std.variant in D which provides type-safe sum types.
alias MyLanguage = VariantN!(<insert types here>);
Re:Implementing a programming language in D: Lexical Analysis
by p0nce on Monday December 28, 2015 @08:13PM
(#10804527)
Like others said, this can be done as a library type in D: http://p0nce.github.io/d-idioms/#Recursive-Sum-Type-with-mat...
edit: not that it proves anything, just that "it can eventually be done".
Re:Implementing a programming language in D: Lexical Analysis
by tomjakubowski on Monday December 28, 2015 @09:19PM
(#10804775)
Can you name the variants to distinguish two variants which "carry" the same types? It wouldn't be as useful if you can't express something like:
enum ConnState {
Disconnected,
Connecting,
Connected(net::TcpSocket),
Transferring(net::TcpSocket),
}
Re:Implementing a programming language in D: Lexical Analysis
by jeremiep on Tuesday December 29, 2015 @12:46AM
(#10805434)
I would probably do it like this in D (disclaimer: I haven't tested this code!)
import std.typecons;
import std.socket;
import std.variant;
struct Disconnected {}
struct Connecting {}
alias Connected = Typedef!(TcpSocket, null, "connected");
alias Transferring = Typedef!(TcpSocket, null, "transferring");
alias ConnState = Algebraic!(Disconnected, Connecting, Connected, Transferring);
You could use plain structs instead of the typedef template for the same result.
Re:Implementing a programming language in D: Lexical Analysis
by p0nce on Tuesday December 29, 2015 @06:45AM
(#10806251)
I see what you mean.
You can create such new types with std.typecons.Typedef https://dlang.org/phobos/std_typecons.html#.Typedef
Though it's less pretty.
Re:Implementing a programming language in D: Lexical Analysis
by felixangell1024 on Monday December 28, 2015 @05:04PM
(#10803662)
Yeah, tagged unions and the pattern matching make things so much nicer. I love a lot of things about Rust, it's got a lot of things right.
Seems like without a construct like this, you'd have to use subclasses or something similar, which (to me) isn't quite as nice.