Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1999
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1999

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Pure Functions in rules

  • To: mathgroup at smc.vnet.net
  • Subject: [mg15975] Re: Pure Functions in rules
  • From: gaylord at ux1.cso.uiuc.edu (richard j. gaylord)
  • Date: Fri, 19 Feb 1999 03:26:59 -0500
  • Organization: university of illinois
  • References: <7ag34l$aie@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

In article <7ag34l$aie at smc.vnet.net>, wself at viking.emcmt.edu (Will Self) wrote:

> It appears that I cannot depend on using a pure function
> in a pattern-matching rule.

> I am quite frankly incensed by the behavior shown in
> In/Out 80, below.  Look at these examples:
> 
> In[73]:=     {1,2,3}/.(m_List->7)
> Out[73]=    7
> 
> In[74]:=     {1,2,3}/.(m_List->(2*m))
> Out[74]=    {2,4,6}
> 
> In[75]:=     2*#& /@ {1,2,3}
> Out[75]=    {2,4,6}
> 
> In[77]:=     f[m_List]:=2*#& /@ m
> 
> In[78]:=     f[{1,2,3}]
> Out[78]=    {2,4,6}
> 
> In[79]:=     {1,2,3}/.m_List->f[m]
> Out[79]=    {2,4,6}
> 
> Now try this:
> 
> In[80]:=     {1,2,3}/.(m_List->(2*#& /@ m))
> Out[80]=    {1,2,3}
> 
> Does anyone (say, at WRI for example) care to comment on
> this?


i'll comment:

i think you have a problem with premature evaluation [not with the use of
anonymous functions in a rule per se ].look at this

In[7]:=
Map[(2*#)&, m]

Out[7]=
m

In[9]:=
Trace[Map[ (2*#)&, m]]

Out[9]=
{(2 #1&)/@m,m}


the problem is that in use lhs -> rhs, the rhs of the rule is evaluated
before its used for substition[and it evaluates to the global variable m
which you introduced in the rule

look at 

Trace[{1,2,3} /. m_List -> Map[ (2*#)&, m] ]


and at

m = 5;
Trace[{1,2,3} /. m_List -> Map[ (2*#)&, m] ]

[i'd put the output here but i'm having a problem copy-pasting from Mma
to  my newswatcher app]


if you use :> instead of -> so that the rhs of the rule is not evaluated
before its applied to the evaluated expression [in this case {1,2, 3} it
works fine.

{1,2,3}/.(m_List:>(2*#& /@ m)) 


note: - i suppose there's some reason you mapping an anonymous function
for doubling the elements of a list onto a list rather than just
multiplying the list by two.
-- 
"I would say life is pretty pointless, wouldn't you, without the movies?"
Vincent Gallo as Johnny Tempi in The Funeral (1996)


  • Prev by Date: Re: Re: Bug?
  • Next by Date: Re: Re: Bug?
  • Previous by thread: Re: Pure Functions in rules
  • Next by thread: Re: Pure Functions in rules