6
$\begingroup$

If evaluating an expression produces an error, it's easy to trap that using Check or Throw...Catch.

How can one trap non-evaluation of an expression, that is, when the output is essentially the same as the input. For example, such an expression might be

 Integrate[(x + 1)^Sin[x], x]

which does partial evaluation (inside) but gives as output:

 Integrate[(1 + x)^Sin[x], x]
$\endgroup$
  • 1
    $\begingroup$ When you wrote "which does partial evaluation (inside)", did you mean that x+1 changed to 1+x? $\endgroup$ – Szabolcs Feb 15 '16 at 15:39
  • $\begingroup$ Yes, that's what I meant by the partial evaluation. I realize that complicates the situation. Perhaps a start would be the case where no such inside evaluation occurs. $\endgroup$ – murray Feb 15 '16 at 15:40
  • 2
    $\begingroup$ I think the most practical would be to check if the head (Integrate) changes. There are many functions which return unevaluated when they are unable to compute a result. In all these cases the head will remain unchanged. I think that in most use cases you will know beforehand if the function you are working with is one of these, thus this should be a good test. $\endgroup$ – Szabolcs Feb 15 '16 at 15:42
  • 1
    $\begingroup$ First I wanted to suggest to do what ValueQ does, i.e. something like SetAttributes[test, HoldAll]; test[expr_] := With[{result = expr}, {Hold[expr] =!= Hold[result], result}]. This tries to be very general but it won't handle that x+11+x thing. But do we really need to be this general? If we want to check if an Integral has computed, it's more robust to check if the head of the result is still Integral. This presumes that we knew beforehand that we were working with Integral and not some arbitrary unknown expression. $\endgroup$ – Szabolcs Feb 15 '16 at 15:46
  • 2
    $\begingroup$ As further confirmation that @Szabolcs approach of cheching the returned head is very sound, a similar idea is found even in the documentation when an example snippet wants to automatically plot the numerical solution to an ODE, but only if NDSolve executes successfully. Look for odeplot in this page: wolfram.com/xid/0i6457z13po9yn453z0phv-cpt47o $\endgroup$ – MarcoB Feb 15 '16 at 16:35

Your Answer

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

Browse other questions tagged or ask your own question.