How Can I Define Tags Within My Code Using Sow/Reap in Mathematica?

  • Thread starter Thread starter Lucid Dreamer
  • Start date Start date
  • Tags Tags
    Mathematica Tags
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 4K views
Lucid Dreamer
Messages
25
Reaction score
0
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:
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:
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?
 
Physics news on Phys.org
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,{}}}

Now kill the kernel and restart with your alternate code

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}}}}}
 
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,{}}}

Now kill the kernel and restart with your alternate code

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: