# Nested If statements

When I do this:

Apply[(If[#2 == what, "yay", If[#2 == whoops, "nay"]]) &, {-5, what}]


I get:

yay


But when I do this:

Apply[(If[#2 == what, "yay", If[#2 == whoops, "nay"]]) &, {-5, whoops}]


I get:

If[whoops == what, "yay", If[whoops == whoops, "nay"]]


This setup does work for numbers:

Apply[(If[#2 == 2, "yay", If[#2 == 3, "nay"]]) &, {-5, 3}]
nay


What I was trying to do was when I got stuck here was define a VertexRenderingFunction in a GraphPlot

VertexRenderingFunction -> ({White, EdgeForm[Black], Disk[#, {2, 1}],
Black, Text[
If[#2 == alpha1, "Alpha",
If[#2 == beta, "Beta",
If[#2 == alpha2, "Alpha",
If[#2 == gamma, "(70,55)",
If[#2 == delta, "(90,50)"]]]]], #1]} &)


What am I doing wrong? Any help will be greatly appreciated. Thanks.

• Try TrueQ[#2==what], etc. or even ===. Or supply a third argument to If. See docs.
– JxB
Commented Sep 27, 2012 at 4:32
• Cool. Thanks JxB. TrueQ[] worked but why was == working on the outside If and not on the inside If? Commented Sep 27, 2012 at 4:44
• See my answer. It should work. Commented Sep 27, 2012 at 4:44
• In similar circumstances you might want to investigate Switch and Which, which are both easier to manage than nested If statements. Commented Sep 27, 2012 at 5:14
• Ok thanks Verbeia, I'll check them out. Commented Sep 27, 2012 at 5:40

At issue is what is being returned by Equals (==). Since both what and whoops do not have values associated with them (OwnValues, in specific), what == whoops returns unevaluated. So, If cannot process it as either True or False, so it remains unevaluated. A way to correct this is to provide a third argument to If, the neither option:

Apply[(If[#2 == what, "yay", If[#2 == whoops, "nay"], "neither"]) &, {-5, what}]
Apply[(If[#2 == what, "yay", If[#2 == whoops, "nay"], "neither"]) &, {-5, whoops}]
(*
"yay"
"neither"
*)


But, I do not believe you wish to use that form. There are three alternatives. First, you can provide values for what and whoops, then the If statement will then be processed. However, if you wish to use them as is, replace Equals with SameQ (===),

Apply[(If[#2 === what, "yay", If[#2 === whoops, "nay"]]) &, {-5, what}]
Apply[(If[#2 === what, "yay", If[#2 === whoops, "nay"]]) &, {-5, whoops}]
(*
"yay"
"nay"
*)


or, as JxB suggest, use TrueQ

Apply[(If[TrueQ[#2 == what], "yay", If[TrueQ[#2 == whoops], "nay"]]) &, {-5, what}]
Apply[(If[TrueQ[#2 == what], "yay", If[TrueQ[#2 == whoops], "nay"]]) &, {-5, whoops}]
(*
"yay"
"nay"
*)


Either expresses your intent, but SameQ requires less typing although it is more difficult to see upon casual inspection.

• awesome!! Thanks! Commented Sep 27, 2012 at 4:46

Following up on Verbeia's comment, it is probably easier to use Which, especially when you get to your Vertex rendering function, which has more nested Ifs. For the present case:

Which[#2 === what, "yay", #2 === whoops, "nay"] & @@ {-5, what}


returns "yay" or "nay" as desired.