# boolean casting

In Mathematica one can do something like the following:

lst = {1, 2, 3};
If[Length[lst] != 0, Print["list is not empty"],
Print["list is empty"]]
(*list is not empty*)


Is there something relevant to automatic Boolean casting?

E.g., for L being a list

If[L,Print["list is not empty"], Print["list is empty"]]


would return list is not empty. That is, using the non-Boolean type with an If statement will cast the first to a Boolean.

As a second example

(*for n being an integer*)
If[n%2,Print["n is odd"],Print["n is even"]


would return n is odd for, e.g. 19.

• I don't think this exists. AFAIK, there is not even an inverse of Boole, i.e., a built-in function that maps {0,1} to {False,True}. Feb 27, 2017 at 21:00

here is how you can implement it yourself:

Clear@if;
if[x_, y_, z_] := Module[{f, g},
(f = Length@x > 0; Switch[f, True, y, _, z]),
Head@x === Integer, (g = Mod[x, 2]; Switch[g, 1, y, _, z])]
]


outputs

if[{}, "list is not empty", "list is empty"]

(* "list is empty" *)

if[{1, 2, 3}, "list is not empty", "list is empty"]

(* "list is not empty" *)

if[20, "n is odd", "n is even"]

(* "n is even" *)

if[19, "n is odd", "n is even"]

(* "n is odd" *)

• Thank you very much for your workaround! Feb 28, 2017 at 10:55

I don't think this is a good idea, but if you really want to you can easily redefine If

Unprotect[If];
If[0, _, b_] := b
If[_?NumericQ, a_, _] := a
Protect[If];

If[0, Print["a"], Print["b"]]
(* b *)

If[1, Print["a"], Print["b"]]
(* a *)