# Book Paul Wellin Prog with math - Rewrite rules

Posted 9 years ago
3861 Views
|
3 Replies
|
1 Total Likes
|
 Hello everybody,I am studing the book of Paul Wellin and I am trying to solve a problem. But I am stuck, This is the question Using ReplaceList write a function 'cartesianproduct' that works with two lists givings CartPr[{{x1,x2},{y1,y2}}] = {{x1,y1},{x1,ÿ2} ,{x2,y1} ...} first tried directly and that worksIn ReplaceList[{{x1, x2, x3}, {y1, y2}}, {{___, a_, ___} , {___, b_, ___}} -> {{a, b}}] Out[11]= {{{x1, y1}}, {{x1, y2}}, {{x2, y1}}, {{x2, y2}}, {{x3, y1}}, {{x3, y2}}} and now the function that doesn't work cartesianProduct[{x_List, y_List}] = ReplaceList[{x, y}, { , a, ___ } , { , b, ___ } -> {a, b}]ReplaceList::innf: Non-negative integer or Infinity expected at position 3 in ReplaceList[{x,y},{,a,},{,b,}->{a,b}]. >>What do I do wrong ?Thanks
3 Replies
Sort By:
Posted 9 years ago
 Works. I made a mistake, which i see now : using "=" instead of " : =" Tried everything but overlooked that. Thank you very much Chiel Geeraert, The Netherlands
Posted 9 years ago
 Your function can be written as: cartesianProduct[{x_List, y_List}] := ReplaceList[{x, y}, {{___, a_, ___}, {___, b_, ___}} -> {a, b}] It should give the desired output: In[]:= cartesianProduct[{{x1, x2, x3}, {y1, y2}}] Out[]= {{x1, y1}, {x1, y2}, {x2, y1}, {x2, y2}, {x3, y1}, {x3, y2}} 
Posted 9 years ago
 last paste repeat  In[10]:= cartesianProduct[{x_List, y_List}] = ReplaceList[{x, y}, {___, a_, ___} , {___, b_, ___} -> {a, b}] During evaluation of In[10]:= ReplaceList::innf: Non-negative integer or Infinity expected at position 3 in ReplaceList[{x,y},{___,a_,___},{___,b_,___}->{a,b}]. >> Out[10]= ReplaceList[{x, y}, {___, a_, ___}, {___, b_, ___} -> {a, b}]enter code here