Anyone come up with some cool algorithms/templates for D lately?

Brian Palmer d at brian.codekitchen.net
Fri Apr 18 09:50:27 PDT 2008


janderson Wrote:

> In the past people have posted these cool algorithms/templates they 
> figured out how to do in some neat way with D.  Things like wow, this 
> would take INF+ lines in C++ but I can do it in 2 in D.   This seems to 
> have died down a bit.   I always found these topics most interesting.
> 
> So I'm requesting people to post "cool stuff" they figured out how to do 
> in D.
> 
> -Joel

I'm not sure if this is the kind of thing you're looking for, but this is a proof-of-concept template that I came up with a few days ago, inspired by a blog post describing similar functionality in Factor [1]. Completely at compile time, it parses a text file describing a mapping between an 8-bit encoding and Unicode, and builds data structures and functions to convert between that encoding and Unicode. The text files are all in a standard format, available at ftp://ftp.unicode.org/Public/MAPPINGS/

Of course, this wouldn't be a big deal to do at runtime with a module constructor, or to simply write a pre-processor to convert each text file to a D module, since they're unlikely to ever change. But I'm pretty new at D and for my own education I wanted to see if I could do all the parsing at compile time so that the full text of the file isn't stored in the executable or bundled with the software.

alias Encoding!("CP1252.txt") windows1252; // ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
auto w1 = "Trademark\x99"; // TM symbol in Windows-1252
auto u1 = "Trademark\u2122"w; // TM symbol in Unicode

wchar[] conv1 = windows1252.toU(w1);
assert(conv1 == u1);

char[]  convback = windows1252.fromU(conv1);
assert(convback == w1);

To be honest I was expecting this to be easier than it was. What I thought would be a trivial experiment ended up taking about an hour, most of that time spent trying different approaches to get CTFE to accept my code. CTFE is a wonderful feature but it's still much, much too limited in what code it will accept, in my opinion.

I've attached the ugly, proof-of-concept code for the module. Please don't think less of me after reading it. :)

[1] http://useless-factor.blogspot.com/2008/04/programming-in-series-of-trivial-one.html
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: encodings.d
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20080418/323fc956/attachment.ksh>


More information about the Digitalmars-d mailing list