How to instantiate a map with multiple functions
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Dec 26 18:21:11 PST 2015
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
More information about the Digitalmars-d-learn
mailing list