Pattern matching in D?

ArturG via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 21 02:49:59 PDT 2016


On Friday, 21 October 2016 at 02:40:45 UTC, Stefan Koch wrote:
> On Friday, 21 October 2016 at 02:16:44 UTC, Chris M. wrote:
>> So I know you can do some pattern matching with templates in 
>> D, but has there been any discussion about implementing it as 
>> a language feature, maybe something similar to Rust's match 
>> keyword (https://doc.rust-lang.org/stable/book/patterns.html)? 
>> What would your guys' thoughts be?
>
> How is this diffrent from "switch-case" ?

switch is a statement, rusts match is an expression and can 
return a value.


i posted this[1] templates a while ago with which you can 
probably do most of what rust can do with the match expressing 
(not tested havent looked into rust much and pattern matching 
isnt the main purpose of them), by combining existing D features.

e.g.

5.call!(a => a == 3? "three" :
	     a == 5? "five"  : "nomatch").writeln;
prints:
five
	
5.call!((a){ a == 3? "three".writeln :
	     a == 5? "five".writeln  : null;}).writeln;
prints:
five
5


[1] http://melpon.org/wandbox/permlink/ngUYhp7SS6uY283b


More information about the Digitalmars-d mailing list