Possible improvement of phobos map?

H. S. Teoh hsteoh at qfbox.info
Wed Jul 6 01:28:32 UTC 2022


On Mon, Jul 04, 2022 at 07:44:11PM +0000, JG via Digitalmars-d wrote:
[...]
> ```d
>   auto a = ["a":5, "b":6];
>   a.byPair.map!(t=>format!"%s=%s"(t[0],t[1])).writeln;
> ```

Yeah, I found this annoying too.


[...]
> With some slight changes to map (which wouldn't be needed if pattern
> matching exists), one can do this:
> 
> ```d
[...]
> a.byPair.mapPrototype!((name,value)=>format!"%s=%s"(name,value)).writeln;
>     [Point(1,2),Point(3,4)].mapPrototype!((x,y)=>x*x+y*y).writeln;
[..]
> ```
> 
> Thoughts?

This is definitely much more pleasant to write.

In fact, I wonder if the current map couldn't be extended to handle
this. We just need .map to detect if the lambda has multiple arguments,
and expand the mapped element accordingly. A lambda argument that takes
two parameters cannot be confused with a lambda argument that takes only
one, so this wouldn't affect existing code. Something like this:

	auto map(alias fun, R)(R range) {
		static if (arity!fun == 1) {
			... // current implementation
		} else {
			... // new implementation, expand element with .tupleof
			    // possibly also check if .tupleof.length
			    // matches arity!fun.
		}
	}


T

-- 
The irony is that Bill Gates claims to be making a stable operating system and Linus Torvalds claims to be trying to take over the world. -- Anonymous


More information about the Digitalmars-d mailing list