# Function generating a rule with a Patterns: e.g. toRule[ lhs, rhs] into lhs[x_] -> rhs [duplicate]

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?

-

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

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]


or

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.

-
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