5
$\begingroup$

I routinely sanitize the inputs to a function using this sort of technique:

funcI[x_Integer] := Print[x];

But it doesn't work with Booleans.

func[x_Boolean] := Print[x];

func[4] (* doesn't execute, as expected *)

func[True] (* doesn't execute, but it should, right? *)

As a workaround, I can use func2[x_ /; BooleanQ[x]] := Print[x];, but why doesn't the simpler formulation work?

func2[True] (* works just fine *)
$\endgroup$

2 Answers 2

9
$\begingroup$

x_Integer is a pattern which catches an x so long as the Head of x is identical to Integer. Booleans have no such head:

{Head[True], Head[False]}

{Symbol, Symbol}

Thus, x_Boolean will not match True or False, since Symbol is not identically equal to Boolean.

You may instead use x_?BooleanQ, which is a pattern which catches an x so long as BooleanQ[x] is identically True.

$\endgroup$
6
$\begingroup$

BooleanQ[] is new in version 10, so eyorble's approach is what I'll recommend for current code. (A hint that your initial approach would not have worked is that neither Head[True] nor Head[False] return Boolean, which is the pattern you were trying to match in your original definition.) In the old days, this is what I'd do (and using a different example):

func[x : True | False] := Boole[x]

func /@ {True, False, π, xxx}
   {1, 0, func[π], func[xxx]}
$\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.