0
$\begingroup$

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?

$\endgroup$
3
  • $\begingroup$ I'm sure this is a duplicate but I can't find it. For a quick fix try toRule[l_, r_] := l[x_] -> #&@ r $\endgroup$ Oct 22, 2013 at 21:23
  • $\begingroup$ 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. $\endgroup$ Oct 22, 2013 at 21:23
  • $\begingroup$ Thank you. This appears to be the problem. It sure appears to be a defect to me. $\endgroup$
    – jlperla
    Oct 22, 2013 at 22:51

1 Answer 1

1
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ Thanks. ToRules[f, a+b, x_] does indeed work. I would guess it is because of the same sorts of trickery mentioned above. $\endgroup$
    – jlperla
    Oct 22, 2013 at 22:53
  • $\begingroup$ 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. $\endgroup$
    – Peltio
    Oct 23, 2013 at 0:57

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