# What's the difference between functions and replacement?

I used to thought that calling a function is equal to applying a rule, i.e. applying a rule of f[x_]->sth. is equal to calling a function f with definition f[x_]:=sth.

However, given

disOut[dot[add[y__], z__]] := dot[#, z] & /@ add[y];

dot[add[a, b, c], d, e, f] // disOut (*would produce*)
add[dot[a, d, e, f], dot[b, d, e, f], dot[c, d, e, f]]


while

dot[add[a, b, c], d, e, f] /. dot[add[y__], z__] -> dot[#, z] & /@ add[y](*would be*)
add[dot[a, b, c, d, e, f]]


Why? What's the difference between functions and replacement?

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Jun 7 '15 at 14:03

Some parentheses and RuleDelayed instead of a Rule:

dot[add[a, b, c], d, e, f] /. dot[add[y__], z__] :> (dot[#, z] & /@ add[y])
(*  add[dot[a, d, e, f], dot[b, d, e, f], dot[c, d, e, f]]  *)


The :> prevents dot[#, z] & /@ add[y] from evaluating until after y and z have been replaced by the expressions they matched.

DownValues shows the rules that a function evaluation uses:

DownValues[disOut]
(*  {HoldPattern[disOut[dot[add[y__], z__]]] :> (dot[#1, z] &) /@ add[y]}  *)


Note that the parentheses may be put in another place, too. The reason you need the parentheses has to do with the precedence of the operators & and Rule/RuleDelayed.

• Thanks a lot! So functions are (delayed) rules after all? – user372021841 Jun 7 '15 at 14:26
• @user372021841 Yes, but the order in which functions and their arguments are evaluated can be influenced by attributes. See tutorial/Evaluation, if you haven't already seen it. – Michael E2 Jun 7 '15 at 15:11
• Not quite. Do a search for functions vs. Patterns. – LLlAMnYP Jun 7 '15 at 16:11
• @LLlAMnYP I believe that is mentioned in the tutorial I linked to, but thanks for a hint to the link for further discussion on the site. The issues are rather broad, technical, and complicated to address, I felt. But when a function like the OP's is evaluated, it is a rule that is being applied, isn't it? – Michael E2 Jun 7 '15 at 17:06
• Yes, the OP gives a replacement rule, function or not on the right hand side. I think that the SetDelayed way of giving DownValues is in a way also defining a replacement rule. I can't say much more, as I'm not that fluent on the internals of Mathematica. – LLlAMnYP Jun 7 '15 at 18:48