Pattern matching in D?

Nick Treleaven via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 28 04:53:16 PDT 2016


On Monday, 24 October 2016 at 04:14:52 UTC, Nick Sabalausky wrote:
> It's just...I mean, yea, it works, and you could probably DRY 
> it up a little with a type contructing template ("alias 
> RgbColor = DoMagic!RgbColor_"), but...meh...

I think the following should be better. Instead of Proxy we would 
have a bespoke mixin which might fix some of the workarounds 
below. In the unittest, using with(Color) should help, but I 
couldn't get that to compile (visit thinks invalid lambdas are 
being passed).

import std.variant;

struct Color {
	struct Custom
	{
		float red;
		float green;
		float blue;
	}

	//mixin NewTypes!`Red, Yellow, Green`;
	struct Red {}
	struct Yellow {}
	struct Green {}

	private auto impl = Algebraic!(
		Custom,
		Red,
		Yellow,
		Green)();
	import std.typecons;
	mixin Proxy!impl;
}

unittest{
	Color color;
	// assignment works but not ctor
	color = Color.Custom(1, 2, 3);
	assert(color.type == typeid(Color.Custom));
	// FIXME: currently need impl
	auto x = color.impl.visit!(
		(Color.Red) => "red",
		(Color.Yellow) => "yellow",
		(Color.Green) => "green",
		(Color.Custom c) =>
			ctFormat!`rgb(%s, %s, %s)`(c.red, c.green, c.blue)
	);
	assert(x == "rgb(1, 2, 3)");
}

// TODO: implement ct parsing
auto ctFormat(string s, Args...)(Args args){
	import std.format;
	return format(s, args);
}



More information about the Digitalmars-d mailing list