Make a hash out of two ranges

Chris Cain clcain at uncg.edu
Wed Feb 27 20:22:57 PST 2013


On Thursday, 28 February 2013 at 03:59:16 UTC, Andrej Mitrovic 
wrote:
> void main()
> {
>     auto r = map!((a, b) => [a : b])([1, 3], [2, 4]);
>     assert(r[0] == [1 : 2]);
>     assert(r[1] == [3 : 4]);
> }

Map in std.algorithm doesn't really work like that. Many 
languages use "map" to mean hashing items, but "map" in 
functional programming (and D) really means something more like 
"apply this function to each item."

So, if you did something like this:

     auto arr = [1,3];
     auto r = map!(a => a + 1)(arr);
     assert(r[0] == 2); // because arr[0] + 1 == 2 ... f(arr[0]) = 
f(1) = 1 + 1 = 2
     assert(r[1] == 4); // because arr[1] + 1 == 4 ... f(arr[1]) = 
f(3) = 3 + 1 = 4

Then you'd have the correct idea.

If you're trying to create an associative array from two arrays, 
zip and associative arrays could be handy:
http://dlang.org/phobos/std_range.html#.zip
http://dlang.org/hash-map.html

So, you could use it like so...

     int[int] aa;
     foreach(a, b; zip([1,3], [2,4]))
         aa[a] = b;

     writeln(aa); // prints [1:2, 3:4]


More information about the Digitalmars-d-learn mailing list