Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to create a rule as a function of z from a left and right hand side. My (non-working) code and usage is:

toRule[l_, r_] := l[x_] -> r

toRule[f, a+b]

I want the output to be:

(* => f[x_] -> a + b*)

However: when I do this with the code above I get:

(* => f[x$_] -> a + b*)

Where is the $ coming from, and how can I get rid of it?

share|improve this question

marked as duplicate by Leonid Shifrin, Artes, Sjoerd C. de Vries, R. M. Oct 22 '13 at 22:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

I'm sure this is a duplicate but I can't find it. For a quick fix try toRule[l_, r_] := l[x_] -> #&@ r – Simon Woods Oct 22 '13 at 21:23
This is the same problem of excessive variable renamings as described here. Use any of the constructs which fool this mechanism, such as toRule[l_, r_] := Rule @@ {l[x_], r} or toRule[l_, r_] := Identity[Rule][l[x_], r], and everything is dandy. But, often such cases are a signal to reconsider what is it you are actually trying to do - the real need for such tricks is rare. – Leonid Shifrin Oct 22 '13 at 21:23
Thank you. This appears to be the problem. It sure appears to be a defect to me. – jlperla Oct 22 '13 at 22:51

Another way to do what you want is via the use of default values.

toRule[left_, right_, var_:x] := Rule[left @@ {var}, right]


Default[toRule] = x
toRule[left_, right_, var_.] := Rule[left @@ {var}, right]

They both work as intended as long as the left argument is the head of a function of the default variable var.

share|improve this answer
Thanks. ToRules[f, a+b, x_] does indeed work. I would guess it is because of the same sorts of trickery mentioned above. – jlperla Oct 22 '13 at 22:53
Actually, toRule[f,a+b] should work too. If you are willing to specify the variable, then you could use the following call syntax: toRule[left_, right_, var_], with the same definition given above. – Peltio Oct 23 '13 at 0:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.