4
$\begingroup$

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)"
expr2 = ToExpression[str2, TraditionalForm]

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?

$\endgroup$
6
  • $\begingroup$ 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. $\endgroup$
    – Nasser
    Apr 24 '17 at 17:34
  • $\begingroup$ @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. $\endgroup$
    – Stitch
    Apr 24 '17 at 17:36
  • 2
    $\begingroup$ 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? $\endgroup$
    – Nasser
    Apr 24 '17 at 17:39
  • 1
    $\begingroup$ What if f has definitions but not for given argument pattern? e.g. f[x_]:=x. $\endgroup$
    – Kuba
    Apr 24 '17 at 19:20
  • 1
    $\begingroup$ @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 $\endgroup$
    – Stitch
    Apr 24 '17 at 20:29
3
$\begingroup$

In:

ClearAll[f, xs, UndefinedQ]
UndefinedQ[x_] := Definition[x] // ToString // "Null" == # &
xs = {f, Power, Sin, Times};
xs // Select[UndefinedQ] 

Out:

{f}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.