Another task

Simen kjaeraas simen.kjaras at gmail.com
Wed Jan 19 17:19:38 PST 2011


bearophile <bearophileHUGS at lycos.com> wrote:

> Now and then I like to test Phobos with simple tasks, to see how it's  
> going.
>
> This simple task is to create a dynamic array of pairs (tuples) like:
> [(10,"aa"), (30,"bb"), (50,"cc")]
>
> from the associative array:
> [1:'a', 2:'b', 3:'c']
>
> If possible read things lazily from the associative array.
>
> ---------------------
>
> Idiomatic Python2 solution (iteritems is lazy):
>
>>>> d = {1:'a', 2:'b', 3:'c'}
>>>> [(k*10, v*2) for k,v in d.iteritems()]
> [(10, 'aa'), (20, 'bb'), (30, 'cc')]
>
> ---------------------
>
> D2 lazy solution without map():
>
> import std.stdio, std.typecons;
> void main() {
>     auto aa = [1:'a', 2:'b', 3:'c'];
>     Tuple!(int, string)[] r;
>     foreach (k, v; aa)
>         r ~= tuple(k*10, ""~v~v);
>     writeln(r);
> }
>
> ---------------------
>
> Alternative D2 lazy solution without append and map():
>
> import std.stdio, std.typecons;
> void main() {
>     auto aa = [1:"a", 2:"b", 3:"c"];
>     auto r = new Tuple!(int, string)[aa.length];
>     int count = 0;
>     foreach (k, v; aa)
>         r[count++] = tuple(k*10, v~v);
>     writeln(r);
> }
>
> ---------------------
>
> Now to test Phobos a little, is it easy to write a D2 lazy version that  
> uses map()? Are you able to write it? How many tries needs a D2  
> programmer with about a month of D2 programming experience to write a  
> correct version that uses map()?

Why use map()? The correct solution for this looks like so:


import std.range;

void main( ) {
     auto aa = [1:"a", 2:"b", 3:"c"];
     auto result = zip( aa.keys, aa.values );
}

-- 
Simen


More information about the Digitalmars-d mailing list