MathGroup Archive 1999

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

Search the Archive

Re: Pure Functions in rules


Hi Will,

the behaviour is correct because you have to use
RuleDelayed[] and

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

works as expected. You can see what's happen with

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

The rhs of Rule[] is evaluated first and gives the final
replacement m_List -> m, because the pure function maps
to a symbol. 

If you have a function f[m_List] defined just the same happens
(m_List -> f[m]) but since m is not a list Mathematica leaves
the result unevaluated until ReplaceAll[] insert the list
in the argument of f[]. Now the pattern for f[m_List] matches
and f[] can multiply the list entries by two.

It is a good rule for the design of replacment rules
to use RuleDelayed[] when in the left hand side of the
rule contain a pattern.

Hope that helps
  Jens

Will Self wrote:
> 
> It appears that I cannot depend on using a pure function
> in a pattern-matching rule.
> 
> Here I am trying to convince reluctant students that they're
> better off learning to use Mathematica than doing things
> by hand, and we run across something like this, and in a
> much more complicated situation where the trouble was
> hard to isolate.
> 
> I am quite frankly incensed by the behavior shown in
> In/Out 80, below.  Look at these examples:

--- snip snap - snip snapp - snip snap ---
> 
> 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?
> 
> Will Self


  • Prev by Date: Re: Re: Bug?
  • Next by Date: Re: Need Mathlink program Example
  • Previous by thread: Re: Pure Functions in rules
  • Next by thread: Re: Pure Functions in rules