There are so many things in Mathematica I think I will never understand. Perhaps today there will be one fewer...
B'[y]/.B->Function[y,y^2]
Outputs 2y. Grand.
expr=y^2; B'[y]/.B->Function[y,expr]
Outputs 0. My usual workaround is
expr=y^2; B'[y]/.B->Function[Y,expr/.y->Y]
But then
expr=y^2; B'[0]/.B->Function[Y,expr/.y->Y]
gives me a 0 is not a valid variable error. But then
B'[0]/.B->Function[y,y^2]
works, so now I'm just confused.
I'm sure there are other (preferred?) ways of using one of the many similar and confusing versions of Hold, ReleaseHold, Inactive, Active, Delayed, Evaluate, etc.
1) What is going on in the evaluation that allows the workaround to work. But not always. And the reason it doesn't work doesn't make other examples not work. I'm usually too impatient to care but find that it leads to such inelegant code that it has finally got the better of me.
2) What is best practice here? A contributing factor to my confusion is the myriad of Hold etc. options I mentioned above that I don't really understand. They're foreign despite me knowing 10 or so other programming languages pretty well (sure, they're not symbolic, but I find Matlab's symbolic library more intuitive at the basic level. Admittedly not done things as advanced as with Mathematica, but this is pretty basic).
B'[y] /. B -> Function[y, Evaluate@expr]? – kglr Jan 29 '19 at 00:06Module[{expr},expr=y^2;B'[y] /. B -> Function[y, Evaluate@expr]]doesn't work, so this doesn't really solve my problem – bjorne Jan 29 '19 at 13:25Moduleis actually causing another issue. Anyway, the following will work:Module[{expr}, expr = y^2; B'[y] /. B -> Function @@ {y, expr}]– xzczd Jan 29 '19 at 13:59Functiononly sees explicit variables, but I haven't yet find a carnonical post that explains this in a detailed enough way, so I've just started a meta-post regarding to the 1st question: https://mathematica.meta.stackexchange.com/q/2414/1871 As to the 2nd question aboutModule, you may want to read this post: https://mathematica.stackexchange.com/q/20766/1871 – xzczd Jan 29 '19 at 14:57