How to instantiate a map with multiple functions

karthikeyan via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 27 06:49:38 PST 2015


On Sunday, 27 December 2015 at 02:21:11 UTC, Ali Çehreli wrote:
> On 12/26/2015 05:26 PM, Karthikeyan wrote:
>
> > if I need to map on a array of tuples will that work with the
> tuple being
> > unpacked or do I need to get it as single element and do
> unpacking myself?
>
> Unfortunately, there is no automatic unpacking of tuples.
>
> The only exception that I know is when tuples are elements of a 
> range (but not a proper slice, in which case the first element 
> is the automatic element index).
>
> import std.stdio;
> import std.typecons;
> import std.range;
> import std.algorithm;
>
> void main() {
>     auto range = 5.iota.map!(i => tuple(2 * i, i * i));
>
>     // automatic tuple expansion:
>     foreach (twice, square; range) {
>         writefln("twice: %s, square: %s", twice, square);
>     }
> }
>
> Prints:
>
> twice: 0, square: 0
> twice: 2, square: 1
> twice: 4, square: 4
> twice: 6, square: 9
> twice: 8, square: 16
>
> The problem is when the same elements are inside a slice:
>
> import std.stdio;
> import std.typecons;
> import std.range;
> import std.algorithm;
>
> void main() {
>     auto range = [ tuple(0, 0), tuple(2, 1) ];
>
>     foreach (twice, square; range) {
>         writefln("twice: %s, square: %s", twice, square);
>     }
> }
>
> Now 'twice' is the automatic index, and 'square' is the entire 
> element (i.e. the tuple):
>
> twice: 0, square: Tuple!(int, int)(0, 0)
> twice: 1, square: Tuple!(int, int)(2, 1)
>
> Ali

I took a local copy of the std.algorithm.iteration as 
myiteration.d and used it for debugging. Commenting out the 
following two lines make this work 
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L461-L463. I don't know why that fails. I filed an issue at the bug tracker.


More information about the Digitalmars-d-learn mailing list