Mathematica 教程 函数 »|教程 »

# Collecting Expressions During Evaluation

In many computations one is concerned only with the final result of evaluating the expression given as input. But sometimes one also wants to collect expressions that were generated in the course of the evaluation. You can do this using Sow and Reap.
 Sow[val] sow the value val for the nearest enclosing Reap Reap[expr] evaluate expr, returning also a list of values sown by Sow

Using Sow and Reap.

Here the output contains only the final result.
 Out[1]=
Here two intermediate results are also given.
 Out[2]=
This computes a sum, collecting all terms that are even.
 Out[3]=
Like Throw and Catch, Sow and Reap can be used anywhere in a computation.
 This defines a function that can do a Sow.
This nests the function, reaping all cases below 1/2.
 Out[5]=
 Sow[val,tag] sow val with a tag to indicate when to reap Sow[val,{tag1,tag2,...}] sow val for each of the tagi Reap[expr,form] reap all values whose tags match form Reap[expr,{form1,form2,...}] make separate lists for each of the formi Reap[expr,{form1,...},f] apply f to each distinct tag and list of values

Sowing and reaping with tags.

This reaps only values sown with tag x.
 Out[6]=
Here 1 is sown twice with tag x.
 Out[7]=
Values sown with different tags always appear in different sublists.
 Out[8]=
The makes a sublist for each form of tag being reaped.
 Out[9]=
This applies f to each distinct tag and list of values.
 Out[10]=
The tags can be part of the computation.
 Out[11]=