Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a program where users can enter mathematica commands that can evaluate to any of the standard numeric types (complex, real, int, etc.), or to boolean values. Moreover the users can enter functions that depend on variables. (For the sake of this post let's assume the variables are all of type complex.)

I want to know if there's a mathematica command that can type-check an arbitrary string. Specifically, I'd want something like

ReturnsComplex[string, assumptions]

that would return true for "1/x + 7x^2 + Sin[x]" but false for "E^x == 5", say. Does anyone know of such a command, or a way to implement one without a huge quantity of work? (Assume that I can identify all the variables in the string and substitute in if necessary.)

share|improve this question
You may be interested in this question: Automatically check student answers in tests – Jens Apr 27 '13 at 17:51
up vote 4 down vote accepted

This is a simple approach that requires you to include the assumptions about all the identified variables in the second argument (I assume that's what you want to do):

returnsComplex[string_, assumptions_] := TrueQ[
  Simplify[(ToExpression[string]) \[Element] Complexes, assumptions]]

returnsComplex["1/x+7x^2+Sin[x]", x \[Element] Complexes]

(* ==> True *)

returnsComplex["E^x\[Equal]5", x \[Element] Complexes]

(* ==> False *)
share|improve this answer
Wow, I feel stupid. Thanks, that's perfect. – Twiffy Apr 27 '13 at 18:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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