3
$\begingroup$

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.

$\endgroup$
  • 2
    $\begingroup$ 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}. $\endgroup$ – Felix Feb 27 '17 at 21:00
2
$\begingroup$

here is how you can implement it yourself:

Clear@if;
if[x_, y_, z_] := Module[{f, g},
Which[Head[x] === List,
(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" *)
|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ Thank you very much for your workaround! $\endgroup$ – Dimitris Feb 28 '17 at 10:55
1
$\begingroup$

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 *)
|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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