4 edited tags
| link
3 Improved formatting
source | link

Here's a simplified version of what I'm trying to do:

SetAttributes[def, HoldFirst]
def[s_Symbol, v_] := (s[x_] :=v= v)
def[f, x^2]
f[3] (* Expected result: 9 *)
(*
==>  x^2
*)
?f (* Expected result: f[x_] := x^2 *)
(*
  Global`f

  f[x$_] := x^2
*)

Obviously the x in the x_ pattern gets replaced by x$. Is there a way I can prevent that? That is, from calling def[f,x^2] I want to result the definition f[x_] := x^2. I don't of course care about the name of the variable, so if the resulting function definition reads f[x$_] := x$^2 I'm fine with that, too.

I tried def[s_Symbol,v_]:=With[{x$=x}, s[x_]:=v], def[s_Symbol,v_]:=With[{x=x$},s[x_]:=v], def[s_Symbol,v_]:=(s[x_]:=v)/.x:>x$

def[s_Symbol, v_] := With[{x$ = x}, s[x_] := v]
def[s_Symbol, v_] := With[{x = x$}, s[x_] := v]
def[s_Symbol, v_] := (s[x_] := v) /. x :> x$

and def[s_Symbol,v_]:=(s[x_]:=v)/.x$:>x,

def[s_Symbol, v_] := (s[x_] := v) /. x$ :> x

but neithernone worked.

Here's a simplified version of what I'm trying to do:

SetAttributes[def,HoldFirst]
def[s_Symbol,v_]:=(s[x_]:=v)
def[f,x^2]
f[3] (* Expected result: 9 *)
(*
==> x^2
*)
?f (* Expected result: f[x_] := x^2 *)
(*
Global`f

f[x$_] := x^2
*)

Obviously the x in the x_ pattern gets replaced by x$. Is there a way I can prevent that? That is, from calling def[f,x^2] I want to result the definition f[x_] := x^2. I don't of course care about the name of the variable, so if the resulting function definition reads f[x$_] := x$^2 I'm fine with that, too.

I tried def[s_Symbol,v_]:=With[{x$=x}, s[x_]:=v], def[s_Symbol,v_]:=With[{x=x$},s[x_]:=v], def[s_Symbol,v_]:=(s[x_]:=v)/.x:>x$ and def[s_Symbol,v_]:=(s[x_]:=v)/.x$:>x, but neither worked.

Here's a simplified version of what I'm trying to do:

SetAttributes[def, HoldFirst]
def[s_Symbol, v_] := (s[x_] := v)
def[f, x^2]
f[3] (* Expected result: 9 *)
(*
  x^2
*)
?f (* Expected result: f[x_] := x^2 *)
(*
  Global`f

  f[x$_] := x^2
*)

Obviously the x in the x_ pattern gets replaced by x$. Is there a way I can prevent that? That is, from calling def[f,x^2] I want to result the definition f[x_] := x^2. I don't of course care about the name of the variable, so if the resulting function definition reads f[x$_] := x$^2 I'm fine with that, too.

I tried

def[s_Symbol, v_] := With[{x$ = x}, s[x_] := v]
def[s_Symbol, v_] := With[{x = x$}, s[x_] := v]
def[s_Symbol, v_] := (s[x_] := v) /. x :> x$

and

def[s_Symbol, v_] := (s[x_] := v) /. x$ :> x

but none worked.

2 edited tags
| link
    Tweeted twitter.com/#!/StackMma/status/241596777063645185
1
source | link