Thread overview | |||||
---|---|---|---|---|---|
|
February 16, 2015 what is the offical way to handle multiple list in map() ? | ||||
---|---|---|---|---|
| ||||
while learning the map function, i've landed on this wikipedia page(http://en.wikipedia.org/wiki/Map_(higher-order_function)). For each language there is a column about handing multiple list, i thought it could be a good idea to see how D handle this: is this the official way ? --- auto fruits = ["apple", "banana", "orange"][]; auto vegies = ["grass", "salad"][]; // 1 list auto yougonna = map!(a => "eat " ~ a)(fruits); // 2 lists auto youreallygonna = map!( `map!(a => "eat " ~ a)(a)` )([fruits, vegies]); writeln(yougonna.stringof, yougonna); writeln(youreallygonna.stringof, youreallygonna); --- which outputs: --- yougonna["eat apple", "eat banana", "eat orange"] youreallygonna[["eat apple", "eat banana", "eat orange"], ["eat grass", "eat salad"]] --- The doc doesn't specify anything about multiple lists. |
February 16, 2015 Re: what is the offical way to handle multiple list in map() ? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Baz | Baz: > is this the official way ? It seems a way to perform nested mapping in D. > --- > auto fruits = ["apple", "banana", "orange"][]; > auto vegies = ["grass", "salad"][]; Those trailing [] are unneded. > auto youreallygonna = map!( `map!(a => "eat " ~ a)(a)` )([fruits, vegies]); Better to use another lambda inside, instead of that string. Bye, bearophile |
February 17, 2015 Re: what is the offical way to handle multiple list in map() ? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Baz | On 02/16/2015 01:51 AM, Baz wrote: > For each language there is a column about handing multiple > list, i thought it could be a good idea to see how D handle > this: I've updated the page with my understanding: http://en.wikipedia.org/wiki/Map_(higher-order_function) I think they mean walking the lists in sync: import std.stdio; import std.algorithm; import std.typecons; import std.range; int func(int a) { return a * 2; } auto func(Tuple!(int, int) t) { return t[0] + t[1]; } void main() { { auto list = [ 1, 10, 100 ]; auto result = list.map!func; writeln(result); } { auto list1 = [ 1, 10, 100 ]; auto list2 = [ 2, 20, 200 ]; auto result = zip(list1, list2).map!func; // <-- HERE writeln(result); } } Ali |
Copyright © 1999-2021 by the D Language Foundation