3
$\begingroup$

In an example from another question, the rhs of a list of rules can be simply extracted:

In[1]:= rules1 = Solve[x + y == 3 && x - y == 6, {x, y}][[1]] 9 3 Out[1]= {x -> -, y -> -(-)} 2 2 In[2]:= rules1 /. Rule -> (#2 & ) 9 3 Out[2]= {-, -(-)} 2 2 

However, when I try the same replacement with a list of rules where the RHS is a pure function, it does not result in a list of the RHS.

In[3]:= rules2 = {MySum -> Total[#1] & , MyProd -> Times[#1] & } Out[3]= {MySum -> Total[#1] & , MyProd -> Times[#1] & } In[4]:= rules2 /. Rule -> (#2 & ) Out[4]= {(#2 & )[MySum, Total[#1]] & , (#2 & )[MyProd, Times[#1]] & } 

How do I correct this?

$\endgroup$

4 Answers 4

4
$\begingroup$

Jason shows the solution. Your input is not in the correct form as in fact the RHS is not a "pure function" but rather the entire rule is. Using the methods described here will show you this:

Mathematica graphics

Another way to look at this is that Rule has a greater binding power than Function:

Precedence /@ {Rule, Function} 
{120., 90.} 

Also see: Parentheses in pure functions: # & vs. ( # &)

$\endgroup$
3
$\begingroup$

It seems to make a difference to wrap pure functions inside a set of parentheses, including the ampersand.

rules2 = {MySum -> (Total[#1] &), MyProd -> (Times[#1] &)}; rules2 /. Rule -> (#2 &) 

gives the result you are looking for.

$\endgroup$
1
$\begingroup$

This works:

rules2 = {MySum -> Total[#1] &, MyProd -> Times[#1] &} rules2 /. Rule[_, p_] :> p (* {Total[#1] &, Times[#1] &} *) 
$\endgroup$
2
  • $\begingroup$ Thanks. It makes sense why your solution works. I still can't see why the other version fails. Your solution seems more general and should work in all cases. What is it about using a the original patter of just 'Rule' that allowed it to work at all on rules1? $\endgroup$ Commented Nov 12, 2012 at 21:30
  • 1
    $\begingroup$ It should be noted that while this solution works, it does so by taking advantage of the structure of rules2 (see FullForm or TreeForm) $\endgroup$ Commented Nov 13, 2012 at 20:11
-1
$\begingroup$

This also works:

 rules2 = {MySum -> Total[#1] &, MyProd -> Times[#1] &} Last /@ rules2 (* {Total[#1] &, Times[#1] &} *) 
$\endgroup$
2
  • $\begingroup$ The output I get does not match what you show. I get: {MySum -> 1, MyProd -> #1}. This is no mystery as the Function has a body of only one argument so Last (or First) is simply returning that body, evaluated. Sorry, but -1. $\endgroup$ Commented Nov 13, 2012 at 17:45
  • $\begingroup$ As a point of reference you can, in this limited case, get the desired results with rules2[[All, {1}, 2]] for the reason described here but it is far better to enter the expression correctly in the first place. $\endgroup$ Commented Nov 13, 2012 at 17:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.