Pattern matching in D?
Nick Sabalausky via Digitalmars-d
digitalmars-d at puremagic.com
Sun Oct 23 20:55:33 PDT 2016
On 10/23/2016 03:38 PM, Chris M wrote:
> On Friday, 21 October 2016 at 19:00:55 UTC, Nick Sabalausky wrote:
>> What I've been really wanting for a long time is the one-two combo of
>> Nemerle's variants and pattern matching:
>>
>> https://github.com/rsdn/nemerle/wiki/Grok-Variants-and-matching
>
> There is std.variant, though I haven't used it much myself and don't
> know how well it compares. Seems like that library would provide a good
> basis for providing pattern matching though.
This is one of those things where language support makes a big
difference (like slices).
Algebraic is the *closest* thing in D that compared to Nemerle's
variants...But honestly, saying std.variant compares to Nemerle's
variants is like saying C can do high-order functions, OOP, and has a
module system. Yea, *technically* you can, but it's so clunky by
comparison that you're really not getting much of the real benefit.
One of the first examples on that page really highlights how it differs
from D:
--------------------------------
// An equivalent std.variant.Algebraic would be clunky by comparison:
variant RgbColor {
| Red
| Yellow
| Green
| Different {
red : float;
green : float;
blue : float;
}
}
--------------------------------
string_of_color (color : RgbColor) : string
{
match (color) {
| RgbColor.Red => "red"
| RgbColor.Yellow => "yellow"
| RgbColor.Green => "green"
| RgbColor.Different (r, g, b) => $"rgb($r, $g, $b)"
}
}
--------------------------------
D can get close, but it's just not so clean, wouldn't scale as well, and
that really does make a difference (just like how many of D's features
are argued by others to be "not that big a deal", but we know that it is
because we use it and know that extra bit of polish D gives makes a big
difference).
And, yea, yea, Manu has a far better color color lib in D, but of course
this is just an illustration of the language construct. It's one of
those things (of which D really does have many - just not this one),
that once you have it available and start using it, it's very
liberating, and loosing it feels like having your hands tied.
It's not my #1 missed feature in D, but it would be nice.
More information about the Digitalmars-d
mailing list