Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Please help with Rule in Mathematica

  1. Jan 16, 2012 #1
    Please help the idiot
    In[] = D[p[x,t],x,t]/.{Derivative[n_,m_][p_][q__]->a^(n+m)}
    Out[] = a2

    In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->a^Plus[n]}
    Out[] = a

    WTF??? Why not a2????

    In the simplest case
    In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->Plus[n]}
    Out []=Sequence[1, 1]

    In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->Plus[n,1]}
    Out []= 3

    In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->(Plus[n,1]-1)}
    Out []= Sequence[1, 1]
    What hell is going on????

    Thank you very much!
    Last edited: Jan 16, 2012
  2. jcsd
  3. Jan 16, 2012 #2
    It's because you are using Rule instead of RuleDelayed.
    This means that the right-hand-side of the rule gets evaluated before you want it to.
    So Plus[n] gets turned into n before n gets replaced with anything. The rule then fires n gets replaced with Sequence[1,1] explaining your last line.

    Everything works as you want if you use
    Derivative[n__][p_][q__] :> a^Plus[n]
    instead of you original
    Derivative[n__][p_][q__] -> a^Plus[n]

    Another option would be
    Derivative[n_,m___][p_][q__] :> a^Plus[n,m]
    which would still work in the case of
    Derivative[n__][p_][q__] -> a^Plus[n]

    The place where the use of Rule instead of RuleDelayed becomes really problematic is if a term on the RHS already has a value. For example, compare the output of
    n = 5;
    D[p[x, t], x, t] /. {Derivative[n__][p_][q__] -> a^Plus[n]}
    n = 5;
    D[p[x, t], x, t] /. {Derivative[n__][p_][q__] :> a^Plus[n]}
    From version 6 and above, Mathematica has syntax highlighting, so you can tell whether a variable is defined, undefined or localized by its color (black, blue or green respectively).
  4. Jan 16, 2012 #3
    Thank you VERY VERY MUCH! I have no words to tell how you helped me
  5. Jan 16, 2012 #4
    Not a problem!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook