Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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, rm -rf 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

1 Answer 1

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.

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.