Reputation: 58435
I just watched this introduction from the Dart Summit. During the talk, this code was put up:
=> new List.generate(100, (y) => renderLine(y));
I'm pretty sure I understand that line. The arrow function is new to me but okay - it looks a little coffee-esque. The point though, was changing this function to run in parallel which was done like this:
=> Parallel.run(new List.generate(100, (y) => () => renderLine(y)));
Can someone explain the syntax of (y) => () => renderLine(y)
?
Upvotes: 4
Views: 71
Reputation: 71783
The (y) => () => renderLine(y)
is a function that returns a function. If you write it without the =>
shorthand, it is the same as:
(y) {
return () {
return renderLine(y);
};
}
This means that the List.generate
calls this function 100 times, with different values for y
. Each call returns a function that will call renderLine
with a different value.
This generates a list of functions (each taking zero arguments).
That list is the argument to Parallel.run
.
So, the code is just using a quick in-line way to create a list, but it is equivalent to:
var tempList = [];
for (int y = 0; y < 100; y++) tempList.add(() => renderLine(y));
Parallel.run(tempList);
The Parallel.run
function expects a list of functions, and will run the functions in parallel, so you get 100 calls to renderLine
executed in parallel, each with a different argument.
Upvotes: 3
Reputation: 1556
I'm guessing (haven't watched the video) that the Parallel.run()
function receives a list (or iterable) of no-arg functions to run in parallel. The List.generate()
constructor takes an int
(length) and a function (which takes one int
as an argument) and generates that many items by calling the function for each int
in the range 0 .. n-1
. So the code new List.generate(100, (y) => renderLine(y))
generates a List
of 100 items, each of which is the result of calling renderLine()
on each index (that is, renderLine(0), renderLine(1), ... , renderLine(99)
).
The code new List.generate(100, (y) => () => renderLine(y))
returns a list of 100 items, aech of which is a function which takes no argumens, and which when called, calls renderLine()
with its index in the list. That is, the list is: () => renderLine(0), () => renderLine(1), () => renderLine(2), ..., () => renderLine(99)
.
I'm guessing Parallel.run()
then runs all those functions in parallel, maybe aggregating the results in a list and returning it? If so, then the code Parallel.run(new List.generate(100, (y) => () => renderLine(y)))
does something similar to new List.generate(100, (y) => () => renderLine(y))
, except in parallel rather than sequentially.
Upvotes: 0
Reputation: 657781
(y) => () => renderLine()
is a function which is passed as second parameter to Parallel.run()
and this function takes one argument and returns a function which doesn't take any argument.
I don't know why it is done this way.
(x, y) => x + y;
is just a shorthand for (x, y) { return x + y; }
Upvotes: 0