Random D geekout

Jacob Carlborg doob at me.com
Fri Apr 20 02:15:56 PDT 2012


On 2012-04-20 06:06, H. S. Teoh wrote:
> I'm writing some code that does some very simplistic parsing, and I'm
> just totally geeking out on how awesome D is for writing such code:
>
> 	import std.conv;
> 	import std.regex;
> 	import std.stdio;
>
> 	struct Data {
> 		string name;
> 		string phone;
> 		int age;
> 		... // a whole bunch of other stuff
> 	}
>
> 	void main() {
> 		Data d;
> 		foreach (line; stdin.byLine()) {
> 			auto m = match(line, "(\w+)\s+(\w+)");
> 			if (!m) continue;
>
> 			auto key = m.captures[1];
> 			auto value = m.captures[2];
>
> 			alias void delegate(string key, string value) attrDg;
> 			attrDg[string] dgs = [
> 				"name": delegate(string key, string value) {
> 					d.name = value;
> 				},
> 				"phone": delegate(string key, string value) {
> 					d.phone = value;
> 				},
> 				"age": delegate(string key, string value) {
> 					d.age = to!int(value);
> 				},
> 				...	// whole bunch of other stuff to
> 					// parse different attributes
> 			];
> 			attrDg errordg = delegate(string key, string value) {
> 				throw Exception("Invalid attribute '%s'"
> 					.format(key));
> 			};
>
> 			// This is pure awesomeness:
> 			dgs.get(key.idup, errordg)(key.idup, value.idup);
> 		}
> 		// ... do something with Data
> 	}
>
> Basically, I use std.regex to extract keywords from the input, then use
> an AA to map keywords to code that implement said keyword.  That AA of
> delegates is just pure awesomeness. AA.get's default value parameter
> lets you process keywords and handle errors with a single AA lookup.  I
> mean, this is even better than Perl for this kind of text-processing
> code!
>
> The only complaint is that I couldn't write auto[string] dgs and have
> the compiler auto-infer the delegate type. :-) Additionally, I wasn't
> sure if I could omit the "delegate(string,string)" after each keyword;
> if that's actually allowed, then this would make D totally pwn Perl!!

I think you should be able to write:

"age": (key, value) {
     d.age = to!int(value);
}

Or perhaps even:

"age": (key, value) => d.age = to!int(value);

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list