digitalmars.D - Algebraic data types
- bearophile (7/7) Jul 26 2008 I have found this page, coming from elsewhere, and it shows interesting ...
I have found this page, coming from elsewhere, and it shows interesting differences between C and languages with algebraic data types: http://www.reddit.com/r/programming/comments/6tjal/treaps_versus_redblack_trees/ (Note that speed-wise OCaml is a very efficient language). On the wikipedia: http://en.wikipedia.org/wiki/Algebraic_data_types Bye, bearophile
Jul 26 2008
Resurrecting this topic, does D have ADTs yet for enums/structs?
Oct 06 2014
NM, I found this:
http://www.digitalmars.com/d/archives/digitalmars/D/Algebraic_Data_Types_in_D_239039.html
"D's Algebraic needs some work, but it's okay for basic usage."
+1 agree
----
import std.stdio;
import std.variant;
struct Red {}
struct Green{}
struct Blue {}
struct RGB
{
int r;
int g;
int b;
}
alias Color = Algebraic!(Red, Green, Blue, RGB);
void main()
{
auto r = Color(RGB(64, 128, 255));
r.visit!(
(Red r) => writeln("Red"),
(Green g) => writeln("Green"),
(Blue b) => writeln("Blue"),
(RGB rgb) => writefln("RGB(%s, %s, %s)", rgb.r, rgb.g, rgb.b),
);
}
Oct 06 2014
On Monday, 6 October 2014 at 16:48:32 UTC, Jonathan wrote:Resurrecting this topic, does D have ADTs yet for enums/structs?Here's a proof of concept: http://www.infognition.com/blog/2014/recursive_algebraic_types_in_d.html struct Const(T) { ... } class Add(T) { ... } alias Exp = Either!(Add, Const); int eval(Exp!int e) { return e.match(a => a.l + a.r, i => i.x); } string show(Exp!string e) { return e.match(a => "(" ~ a.l ~ " + " ~ a.r ~ ")", i => i.x.text); }
Oct 06 2014









"Jonathan" <jadit2 gmail.com> 