Parsing a string within a block using ToExpression
- To: mathgroup at yoda.physics.unc.edu
- Subject: Parsing a string within a block using ToExpression
- From: Joseph G. McWilliams <mcwilljg at euler.sfasu.edu>
- Date: Thu, 9 Dec 93 15:54:21 -0600
Using the Input[] function, one can enter and parse a function of x by sequential application of ToString[] and ToExpression[]; e.g., if fx is assigned the value x^2 + Cos[x] via Input[], one can convert this to a legitimate delayed evaluation expression by fxStrng = ToString[fx] f[x_] = ToExpression[fxStrng] I have used this method for function input in many programs that prompt the user through use of Input[]. However there is a breakdown in the parsing done by ToExpression[], when these two lines are used within a block structure when writing a function. If, in the function below, fncxy is passed the value x^2 + Cos[x^3], f[x,y] is assigned the expression x + Cos[x], although the string, fxy, is "x^2 + Cos[x^3]". someFunction[fncxy_] := Block[{}, fxy = ToString[fncxy]; f[x_,y_] = ToExpression[fxy] ] The issue can be forced by passing fncxy a string, as in someFunction["x^2 + Cos[x^3]",....], but this is to be used by my students and there is a need to keep the input as simple and straight forward as possible. My questions are: (1) Why am I getting different behavior within and without a block structure? (2) Is there perhaps a simpler, more consistent method of accomplishing the input of a function of x? Any suggestions would be greatly appreciated. --- Joseph McWilliams Mathematics, Stephen F. Austin St.U. Nacogdoches, TX mcwilljg at euler.sfasu.edu