wolfram mathematica - Using Evaluate with a Pure Function and SetDelayed -
i want evaluate f below passing list function:
f = {z[1] z[2], z[2]^2}; = % /. {z[1]-> #1,z[2]-> #2}; f[z_] := evaluate[a] & @@ z ; so if try f[{1,2}] {2, 4} expected. looking closer ?f returns definition
f[z_] := (evaluate[a] &) @@ z which depends on value of a, if set a=3 , evaluate f[{1,2}], 3. know adding last & makes evaluate[a] hold, elegant work around? need force evaluation of evaluate[a], improve efficiency, a in fact quite complicated.
can please out, , take consideration f has contain array[z,2] given unknown calculation. writing
f[z_] := {z[[1]]z[[2]],z[[2]]^2} would not enough, need generated automatically our f.
many contribution.
please consider asking future questions @ dedicated stackexchange site mathematica.
questions less become tumbleweeds , may viewed many experts.
you can inject value of a body of both function , setdelayed using with:
with[{body = a}, f[z_] := body & @@ z ] check definition:
definition[f] f[z$_] := ({#1 #2, #2^2} &) @@ z$
you'll notice z has become z$ due automatic renaming within nested scoping constructs behavior same.
in comments said:
and again bothers me if values of
z[i]changed, workaround fail.
while should not problem after f[z_] defined above, if wish protect replacement done a use formal symbols instead of z. these entered e.g. esc$zesc formal z. formal symbols have attribute protected , exist avoid such conflicts this.
this looks better in notebook here:
f = {\[formalz][1] \[formalz][2], \[formalz][2]^2}; = f /. {\[formalz][1] -> #1, \[formalz][2] -> #2}; another approach replacements inside hold expression, , protect rules evaluation using unevaluated:
clearall[f, z, a, f, z] z[2] = "fail!"; f = hold[{z[1] z[2], z[2]^2}]; = f /. unevaluated[{z[1] -> #1, z[2] -> #2}] // releasehold; with[{body = a}, f[z_] := body & @@ z ] definition[f] f[z$_] := ({#1 #2, #2^2} &) @@ z$
Comments
Post a Comment