# Please explain this pattern/Message related issue and help with finding workaround

I attempted to clean up my code and also add messages to functions if they are called with wrong arguments. This introduced some error which I tracked down to the following:

ClearAll[fun, rep, x, y];
General::argerr = "Something is wrong with arguments passed to the function. Either wrong number or no numerical values.";
fun[var1_?NumericQ, var2_?NumericQ] := Print["everything okay. Sum: ",var1 + var2];
fun[args__] := Message[fun::argerr];

rep = {x -> 2, y -> 3};
fun[x, y] /. rep

fun::argerr: Something is wrong with arguments passed to the function. Either wrong number or no numerical values. *)


This is what I expected since both x,y are non-numerical when fun is called. What is surprising (to me): Just comment out the fun[args__] part and the evaluation of fun[x,y]/.rep yields the result (* everything okay. Sum: 5 *). I'd still expect the function to be called with symbolic x,y, hence failing since non-numerical values which should (as I understood it) output something like fun[x,y]/.{x->2,y->3}.

So to me, two questions are arising:

• How come, that getting rid of the custom message makes the code output the sum of both arguments?
• What would be a way to keep the message and still be able to apply the ReplaceAll (unfortunately I need the replacement at some point)? This fun[x/.rep,y/.rep] works but I failed to implement this for arbitrary amount of arguments. I tried to play with Map but didn't succeed for this.

## 1 Answer

Ad 1

After commenting the second definition, fun[x,y] was evaluated and left in this form since no definition was provided for symbolic arguments. Then the replacement was done and tutorial/Evaluation says:

[...] in evaluating an expression like h[e1, e2, ...]. Every time the expression changes, the Wolfram Language effectively starts the evaluation sequence over again.

So it was evalauted again, this time the definition was found.

Ad 2

I suppose this is way you need:

fun @@ ({x, y} /. rep)


p.s. you can always use Trace to get initial guess about what was done. Like fun[x, y] /. rep // Trace // Column and fun @@ ({x, y} /. rep) // Trace//Column

• Many thanks for this answer! Short while still being extremely informative and helpful. – Lukas Nov 24 '15 at 10:52