Message Boards Message Boards

0
|
4669 Views
|
3 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Book Paul Wellin Prog with math - Rewrite rules

Posted 11 years ago

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 works

In

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

POSTED BY: Chiel Geeraert
3 Replies
Posted 11 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 BY: Chiel Geeraert
Posted 11 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 BY: Girish Arabale
Posted 11 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`
POSTED BY: Chiel Geeraert
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract