Here is an amusing little function mapped over a range just to iterate it. It ignores its argument and works entirely by side-effecting a global variable:
n$ = 1;
Map[(n$ = (n$++) + n$) &, Range[5]]
{3, 7, 15, 31, 63}
Here is a version of the same thing, just using Reap
and Sow
:
n$ = 1;
Reap[Map[Sow[n$ = (n$++) + n$] &, Range[5]]][[1]]
{3, 7, 15, 31, 63}
Here is a version that evaluates the function in an asynchronous task, capturing the result in a Dynamic
(you'll have to key it in to a notebook, or evaluate the SEUploader (courtesy of @halirutan) notebook I linked at the end of this post, to see the variable n$
updating dynamically):
n$ = 1;
Dynamic[n$]
RunScheduledTask[n$ = (n$++) + n$, {0.25, 5}];
63
Clean up the task:
RemoveScheduledTask[ScheduledTasks[]]
Now, here is an attempt to also capture the results in a Reap
(notice no semicolon at the end; I want to see the results of the Reap
as well as to see the Dynamic
):
n$ = 1;
Dynamic[n$]
Reap[RunScheduledTask[Sow[n$ = (n$++) + n$], {0.25, 5}]]
63
{ScheduledTaskObject[7, HoldForm[Sow[n$ = Increment[n$] + n$]], {0.25, 5},
Automatic, True, "AutoRemove" -> False, "EpilogFunction" :> Null,
"TaskGroup" -> "Global`"], {}}
and its cleanup
RemoveScheduledTask[ScheduledTasks[]]
Evidently, the Reap
is evaluated too early and the sown results are lost. How can I get the intended results?
Here's the entire notebook, SE-Uploaded (just evaluate the following expression in a fresh notebook):
Import["http://goo.gl/NaH6rM"]["http://i.stack.imgur.com/x1zYS.png"]
Answer
You can't do this that way,
when you evaluate RunScheduledTask
you are only sending a held procedure for scheduled evaluation to Kernel. But Reap[expr]
:
gives the value of expr together with all expressions to which
Sow
has been applied during its evaluation.
RunScheduledTask
is of course HoldFirst
so Sow
is not applied at this time.
You can put Reap
inside but the you will need also some temporary variable to be able to retrive reaped value from scheduled evaluation.
Comments
Post a Comment