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:
![With the definition AlgebraicQ(a_) := Element(a, Algebraics), the function AlgebraicQ[Pi+E] returns Element(E+Pi, Algebraics) instead of the desired AlgebraicQ(Pi+E). Parens used in place of brackets because of platform limitations.](../../images/b94a8c69823aa0de2a7f15dd5f0f6e02.webp)
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]}
TrueorFalsefor any expression it is given. – m_goldberg May 22 '14 at 13:54AlgebraicIntegerQhas 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?) – Charles May 22 '14 at 13:58AlgebraicsQ[x_Real] := Element[x, Algebraics]works as you want. – gpap May 22 '14 at 14:07Real, but for aRealit 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. – Charles May 22 '14 at 14:10AlgebraicQ /@ {7, Pi, Pi + E, I}? – Charles May 22 '14 at 14:15Head. But you seems to be sure, mistakes happen to me and I don't have any reason not to trust you so: I'm sorry, I should be more careful. :) You may want to delete old not relevant comments too. – Kuba May 22 '14 at 18:42TrueorFalse. I don't understand why! – gpap May 23 '14 at 08:38