Discussion:
Algebraic data types
bearophile
2008-07-26 17:14:38 UTC
Permalink
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
Jonathan via Digitalmars-d
2014-10-06 16:48:30 UTC
Permalink
Resurrecting this topic, does D have ADTs yet for enums/structs?
Jonathan via Digitalmars-d
2014-10-06 16:53:51 UTC
Permalink
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),
);
}
thedeemon via Digitalmars-d
2014-10-07 05:30:40 UTC
Permalink
Post by Jonathan via Digitalmars-d
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);
}

Continue reading on narkive:
Loading...