map with void fun

bearophile bearophileHUGS at lycos.com
Sat Apr 6 14:40:35 PDT 2013


cal:

> Should the code below print anything (it currently doesn't)? 
> I'm not sure I understand map:
>
> import std.stdio, std.algorithm;	
>
> void main() {
>     int[] a = [1,2,3,4,5];
>     auto r = a.map!( i => writeln(i) );
>     while(!r.empty) r.popFront();
> }

The code is working as requested. But there are problems at 
various levels.

First, to see the side effects you have also to call front:

import std.stdio, std.algorithm;
void main() {
     auto a = [1, 2, 3, 4, 5];
     auto r = a.map!(x => writeln(x));
     while(!r.empty) {
         r.front;
         r.popFront;
     }
}

That prints:
1
2
3
4
5


But this is wrong still. map() is a higher order function, it's 
meant to take a function and an iterable and produce a new lazy 
iterable that contains the ordered results of applying the given 
function on each item. writeln() returns nothing (void, it's a 
type with just one value, void itself).

So one more meaningful way to do that is:

import std.stdio, std.algorithm, std.conv;
void main() {
     auto a = [1, 2, 3, 4, 5];
     a.map!text.writeln;
}

That prints:

["1", "2", "3", "4", "5"]

But writeln is well designed, so it's able to take a range, so 
this is better:

import std.stdio, std.algorithm;
void main() {
     auto a = [1, 2, 3, 4, 5];
     a.writeln;
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list