Pattern matching in D?
Nick Sabalausky via Digitalmars-d
digitalmars-d at puremagic.com
Sun Oct 23 21:14:52 PDT 2016
On 10/23/2016 11:55 PM, Nick Sabalausky wrote:
>
> --------------------------------
> // An equivalent std.variant.Algebraic would be clunky by comparison:
> variant RgbColor {
> | Red
> | Yellow
> | Green
> | Different {
> red : float;
> green : float;
> blue : float;
> }
> }
> --------------------------------
Just to compare to equivalent D:
--------------------------------
struct RgbColor_ // Don't clutter the namepsace
{
struct Red {}
struct Yellow {}
struct Green {}
struct Different {
float red;
float green;
float blue;
}
}
alias RgbColor = Algenraic!(
RgbColor_.Red,
RgbColor_.Yellow,
RgbColor_.Green,
RgbColor_.Different,
}
--------------------------------
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...
And then the pattern matching end would be similarly "ehh...meh...":
--------------------------------
RgbColor color = ...;
auto x = color.visit(
(RgbColor_.Red a) => "red",
(RgbColor_.Yellow a) => "yellow",
(RgbColor_.Green a) => "green",
(RgbColor_.Red a) =>
mixin(interpolateStr!`rgb(${a.red}, ${a.green}, ${a.blue})`),
);
--------------------------------
Again, technically works, but...ehh, it's like doing slices or
high-order funcs in C.
More information about the Digitalmars-d
mailing list