# Verify that an expression can be evaluated

Suppose I have a string:

str="sin(x)*25+exp(1.5*y)"


I want to be able to evaluate it in Mathematica. I can do this, of course:

expr=ToExpression[str,TraditionalForm]


E^(1.5 y) + 25 Sin[x]

Now I can use this expression to construct a function or simply evaluate it. The problem is that some of the functions in the string could be custom functions that may or may not be defined in Mathematica already, such as

str2="sin(x)*25+exp(1.5*y)+f(x*y)"


E^(1.5 y) + f[x y] + 25 Sin[x]

I want to verify that all the functions in the expr2 are defined, in other words, the expression can be evaluated.

I can do:

Cases[expr2, x_[__] :> x, Infinity] // Union


{f, Power, Sin, Times}

But how to verify that all of the functions have been defined already? Are the other ways to approach the problem?

• I think you can look at the DownValues of the symbol. If your symbol has associated transformation (i.e. already been defined) then it will not be empty, else you'll get empty list. Apr 24 '17 at 17:34
• @Nasser Good idea, but the problem is that DownValues of all built-in functions are empty, and I don't know how to distinguish between built-in and custom functions. Apr 24 '17 at 17:36
• That is correct, but may be check the context also. Context[Power] and Context[Sin] etc.. all give System. So one way might be to check the context first, and for those not in System only then look if they have DownValues? Apr 24 '17 at 17:39
• What if f has definitions but not for given argument pattern? e.g. f[x_]:=x.
– Kuba
Apr 24 '17 at 19:20
• @Kuba This is potentially a problem, but as a first approximation I think I can assume that there is either no function defined at all or the correct function exists if it is defined. It's a right question though and it might probably require further analysis of DownValues Apr 24 '17 at 20:29

ClearAll[f, xs, UndefinedQ]

{f}