3
$\begingroup$

Is it possible to achieve pattern test inside a pure function? I have tried

f = Function[{x_?NumericQ},
    x
]

but the error Function::flpar occured.

$\endgroup$
3
  • 3
    $\begingroup$ No, this is not possible. f = Replace[x_?NumericQ :> x^2] is the closest thing you get. $\endgroup$ Apr 20, 2023 at 12:53
  • $\begingroup$ Welcome to the community. You can achieve a similar effect with If[MatchQ[x, _?NumericQ], ...], the only difference is when it doesn't match, you'll get an unevaluated expression normally but with If you can control what to return. $\endgroup$
    – Ben Izd
    Apr 20, 2023 at 12:54
  • $\begingroup$ What is your larger objective? Without any other context, I'd say don't set f equal to a Function but instead give it DownValues. Is there a reason why you can't do that? $\endgroup$
    – lericr
    Apr 20, 2023 at 14:50

1 Answer 1

1
$\begingroup$

You may do the pattern test inside the function and eventually return immediately without further evaluation. E.g.

f = (If[! NumericQ[#], "Argument not numeric", #^2]) &;

f[a]
Argument nnot numeric

f[2]
4
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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