Algebraic Data Types in D?

Meta via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 31 16:23:00 PDT 2014


On Thursday, 31 July 2014 at 20:28:55 UTC, Remo wrote:
> How to translate this useless Rust code to D, with as least D 
> code as possible ?
> How be sure that everything will still work as expected if 
> programmer will add White color ?
>
>   enum Color {
>     Red,
>     Green,
>     Blue,
>     Rgb(int,int,int)
>   }
>
>   fn main() {
>     let r = Rgb(64,128,255);
>     match r {
>       Red   => println!("Red"),
>       Green => println!("Green"),
>       Blue  => println!("Blue"),
>       Rgb(r,g,b)   => println!("Rgb({},{},{})",r,g,b),
>     }
>   }

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),
	);
}

D's Algebraic needs some work, but it's okay for basic usage. The 
most annoying thing is that you can't instantiate an RGB and 
expect the compiler to magically know that it's a subtype of 
Color. Maybe there's a way to work around that, but I can't think 
of one right off.


More information about the Digitalmars-d mailing list