5

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.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Amatya
  • 6,888
  • 3
  • 26
  • 35

2 Answers2

11

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.

rcollyer
  • 33,976
  • 7
  • 92
  • 191
1

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.

bill s
  • 68,936
  • 4
  • 101
  • 191