0
$\begingroup$

It is possible to define function dependently to passed argument type or condition this argument fulfills (somewhat like overloading):

g[x_?EvenQ] := Print[ToString[x] <> " Is even"]
test1 = (TrueQ[# < 1]) &; test2 := (TrueQ[# >= 1]) &;
g[x_Real ? test1] := Print["function for real x of value < 1"]
g[x_Real? test2] :=Print["function for real x of value >= 1"]

Is it possible to use for this purpose lambda function (anonymous function / pure function) so I don't have to define test1 or test2 and simply use:

g[x_Real ?(TrueQ[# < 1]) &] := Print["function for real x of value < 1"]
g[x_Real ?(TrueQ[# >= 1]) &] :=Print["function for real x of value >= 1"]

instead? In first case g[0.25] returns function for real x of value < 1 in second case it remains unevaluated.

$\endgroup$
  • 1
    $\begingroup$ you can also use /; (Condition). $\endgroup$ – Spawn1701D May 21 '13 at 18:43
  • 1
    $\begingroup$ Just check the precedence of ?. Use extra brackets. g[x_Real ?(TrueQ[# < 1] &)] $\endgroup$ – Rojo May 21 '13 at 18:47
  • $\begingroup$ Both solutions (by Spawn1701D and Rojo) work, however I needed What Rojo suggested. g[x_Real ?((TrueQ[# < 1]) &)] := Print["function for real x of value < 1"] $\endgroup$ – Misery May 21 '13 at 18:49
  • 3
    $\begingroup$ Related: (1), (2) $\endgroup$ – Mr.Wizard May 21 '13 at 18:56
  • 1
    $\begingroup$ @Misery You can leave out the inner () and you don't need TrueQ because < will always give True/False for real numerical values and that is guaranteed by your use of _Real. In other words, g[x_Real?(# < 1 &)] := ... is the same. $\endgroup$ – rm -rf May 21 '13 at 21:01