# Mathematica: tags in Reap/Sow

1. Jun 4, 2012

### Lucid Dreamer

I am trying to use Sow/Reap in Mathematica to replace Append in my code. The problem is that I need to define the tags within my code, but doing so doesn't reap the desired results. A simplified version of my code is

Code (Text):

Clear[tag];
Reap[tag = {a,b}; Sow[1, a];Sow[2,b];, tag]

However, if I define my tag outside of Reap, then it works

Code (Text):

Clear[tag];
tag = {a,b};
Reap[Sow[1, a];Sow[2,b];, tag]

Any ideas as to how I can define tags within my code?

2. Jun 5, 2012

### Bill Simpson

Trace gives some hints about what is going on

In[1]:= Clear[tag]; Trace[Reap[tag={a,b};Sow[1,a];Sow[2,b];,tag]]

Out[2]= {Reap[tag={a,b};Sow[1,a];Sow[2,b];,tag], {tag={a,b};Sow[1,a];Sow[2,b];,{tag={a,b},{a,b}},{Sow[1,a],{Message[Sow::enclt,a,Sow[1,a]],{Sow::enclt,$Off[Tag 1 in 2 has no matching Reap.]},Null},1},{Sow[2,b],{Message[Sow::enclt,b,Sow[2,b]],{Sow::enclt,$Off[Tag 1 in 2 has no matching Reap.]},Null},2},Null},{Null,{}}}

In[1]:= Clear[tag];tag={a,b}; Trace[Reap[Sow[1,a];Sow[2,b];,tag]]

Out[3]= {{tag,{a,b}},Reap[Sow[1,a];Sow[2,b];,{a,b}],{Sow[1,a];Sow[2,b];,{Sow[1,a],1},{Sow[2,b],2},Null},{Null,{{{1}},{{2}}}}}

3. Jun 5, 2012

### Bill Simpson

Trace gives some hints about what is going on

In[1]:= Clear[tag]; Trace[Reap[tag={a,b};Sow[1,a];Sow[2,b];,tag]]

Out[2]= {Reap[tag={a,b};Sow[1,a];Sow[2,b];,tag], {tag={a,b};Sow[1,a];Sow[2,b];,
{tag={a,b},{a,b}},
{Sow[1,a],{Message[Sow::enclt,a,Sow[1,a]],{Sow::enclt,$Off[Tag 1 in 2 has no matching Reap.]},Null},1}, {Sow[2,b],{Message[Sow::enclt,b,Sow[2,b]],{Sow::enclt,$Off[Tag 1 in 2 has no matching Reap.]},Null},2},Null},
{Null,{}}}

In[1]:= Clear[tag];tag={a,b}; Trace[Reap[Sow[1,a];Sow[2,b];,tag]]

Out[3]= {{tag,{a,b}},Reap[Sow[1,a];Sow[2,b];,{a,b}],{Sow[1,a];Sow[2,b];,{Sow[1,a],1},{Sow[2,b],2},Null},
{Null,{{{1}},{{2}}}}}

This is interesting, notice the comma I removed from your nonworking example and the missing warning messages

In[1]:= Clear[tag];Trace[Reap[tag={a,b};Sow[1,a];Sow[2,b];tag]]

Out[2]= {Reap[tag={a,b};Sow[1,a];Sow[2,b];tag],{tag={a,b};
Sow[1,a];Sow[2,b];tag,{tag={a,b},{a,b}},
{Sow[1,a],1},{Sow[2,b],2},{tag,{a,b}},{a,b}},
{{a,b},{{1},{2}}}}

But that raises at least as many questions as your original

Last edited: Jun 5, 2012