The error is in the placement of &
. Looking at the FullForm
of the left hand sides
FullForm[a[x_Real?(# > 0) &]]
(*
a[Function[PatternTest[Pattern[x,Blank[Real]],Greater[Slot[1],0]]]]
*)
and
FullForm[a[x_Real /; (# > 0) &]]
(*
a[Function[Condition[Pattern[x,Blank[Real]],Greater[Slot[1],0]]]]
*)
shows that, in both cases the entire pattern is considered part of the function. To solve this, simply move the ampersand (&
) inside the parantheses. In other words,
a[x_Real?(# > 0&)] := Plot[x*Sin[y], {y, 0, 10}];
a[x_Real/;(# > 0&)] := Plot[x*Sin[y], {y, 0, 10}];
Edit: This includes an explanation, now, about why the form using Condition
, above, does not work.
However, the condition will not work as expected as it does not apply a function to the parameter, but evaluates the condition with the variable set to its passed in value. It is equivalent to this
TrueQ@Block[{x = (* some value *)}, (* condition *)]
In your case, the condition is # > 0&
, so TrueQ
will return False
. Instead you want to use the variables name inside of the condition, as follows
a[x_Real/;(x > 0)] := Plot[x*Sin[y], {y, 0, 10}];
As pointed out by Heike, there is another problem: 5
is interpreted by Mathematica as Integer
not Real
, so a[5]
will only return a[5]
. There are two ways to handle this, fix it by removing the restriction
a[x_?(# > 0&)] := Plot[x*Sin[y], {y, 0, 10}];
a[x_/;(x > 0)] := Plot[x*Sin[y], {y, 0, 10}];
or, ensure that a real number is passed: