Another task
bearophile
bearophileHUGS at lycos.com
Wed Jan 19 15:49:52 PST 2011
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()?
Bye,
bearophile
More information about the Digitalmars-d
mailing list