Mathjax

Tuesday, October 8, 2013

Ambiguous Pattern Matching in Mathematica

I was tripped up in this ambiguity within Mathematica's pattern matching. This is the behavior I want:

In[92]:= {{"a", 1}, {"c", 2}, {"e", 3}} /. {t_, w_} -> {Null, t, w, Null}
Out[92]= {{Null, "a", 1, Null}, {Null, "c", 2, Null}, {Null, "e", 3, Null}}

However, if the list has only two items in it, then the output is:

In[91]:= {{"a", 1}, {"c", 2}} /. {t_, w_} -> {Null, t, w, Null}
Out[91]= {Null, {"a", 1}, {"c", 2}, Null}


One of the ways to correct the issue (if possible) is to constrain the patterns further, such as:

In[99]:= {{"a", 3}, {"c", 4}} /. {t_String, w_Integer} -> {Null, t, w, Null}
Out[99]= {{Null, "a", 3, Null}, {Null, "c", 4, Null}}



No comments:

Post a Comment