How do I get Mathematica to return a function call (conditionally) unevaluated? I expect this may use the slightly-mysterious Hold
function.
As a toy example, suppose I want to define AlgebraicQ
such that AlgebraicQ[x]
returns True
or False
when Element[x, Algebraics]
evaluates to True
or False
, but otherwise to returns AlgebraicQ[x]
, just like the other predicate functions do. (I can't just ask if Element[x, Algebraics] == True
, because this is itself unevaluated.)
Edit: The first thing that came to mind didn't work, as you can see:
I had tried this before posting, but on a recommendation I tried again with a fresh kernel (pictured above) with the same results. I also tried
AlgebraicQ[a_] := True /; Element[x, Algebraics]
AlgebraicQ[a_] := False /; ! Element[x, Algebraics]
based on an earlier suggestion but this seems not to work at all.
Final working solution
based on Szabolcs' answer:
AlgebraicQ[a_] := With[{result = Element[a, Algebraics]},
result /; MatchQ[result, True | False]]
which tests as expected:
AlgebraicQ /@ {7, Pi, Pi + E}
Out[2]= {True, False, AlgebraicQ[E + Pi]}
True
orFalse
for any expression it is given. $\endgroup$AlgebraicIntegerQ
has precisely the same behavior I'm describing. (How could a function possibly guarantee to return True or False when the answer is not even known to mathematicians?) $\endgroup$AlgebraicsQ[x_Real] := Element[x, Algebraics]
works as you want. $\endgroup$Real
, but for aReal
it should returnElement[x, Algebraics]
because that's what you're telling it to return. Very strange, I'd be interested to learn more about this case. $\endgroup$