I'm trying to write a function whose first argument must be another function, defined either as a pure function or a function-style replacement rule. I don't know how to specify a condition on the argument to achieve that. I know I can use g[func_Function,…] to require pure functions, but functions defined via replacement rules don't have a useful Head.
Here's an example:
f[x_] := x^2 - 1;
g[func_?MatchQ[#, _[___]] &, a_, b_] := func[a + b];
g[f, 1, 2]
(* g[f, 1, 2] *)
Checking the Head of f doesn't seem helpful:
Head[f] (* ==> Symbol *)
Head[f[x]] (* ==> Plus *)
How can I constrain the arguments to g such that it will accept either a pure function or a function defined with :=?
System'Private'MightEvaluateWhenAppliedQin the page you linked to, but I could't get it to do anything. Every time I tried using it, I just got my expression back unevaluated. :( – ibeatty Nov 08 '17 at 20:49System`Private`MightEvaluateWhenAppliedQ[f], thenf[x_] := x^2, thenSystem`Private`MightEvaluateWhenAppliedQ[f]again. – Szabolcs Nov 10 '17 at 12:30f[x_?NumberQ] := x^2then neither off[x]orf[Pi]orf[Sqrt[2]]will evaluate. Ifx /: g[x] = 1thenMightEvaluateWhenAppliedQ[g]isFalsebutg[x]evaluates. While this is a contrived example, UpValues are really used like this in practice. This is how many of the group theory functions are implemented for groups not represented as permutation groups. – Szabolcs Nov 10 '17 at 13:03f[___]:=and pure functions is adequate. – ibeatty Nov 11 '17 at 18:56x^2+1where#^2 + 1&is needed. Viewed that way, it makes sense. – Szabolcs Nov 11 '17 at 18:59