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"]["https://i.stack.imgur.com/x1zYS.png"]