# Efficient and compact replacement for Association in the following case

Consider the following association:

WhatToDo[y_, condition1_, condition2_] :=
Association[{{y, "True", "False"} ->
NIntegrate[
Exp[-x^y]*Cos[(z + x)^y], {x, 0.1, 5}, {z, 0.2, 7}], {y, "True",
"True"} ->
Max[Table[
RegionDistance[
Ball[{0.5, 12, 0.1}, y^i], {y^0.3, y, y^-0.8}], {i, 0.1, 1,
0.1}]], {y, "False", "True"} ->
ArcTan[1/y], {y, "False", "False"} ->
Table[{i,
NIntegrate[
Exp[-x^(y*i)]*Cos[(z + x)^(y*i)], {x, 0.1, 5}, {z, 0.2,
7}]}, {i, 0.1, 1, 0.1}]}][{y, condition1, condition2}]


It is stupid since even if fixing any of the arguments it still evaluates for all possible combinations. An ugly alternative would be using If, but the code would be very bulky. Could you please tell me what is the analog of Association that is compact and simultaneously does not call evaluations for all the possible combinations here?

Just try to replace in your Association all Rule ("->") with RuleDelayed ":>".

WhatToDo2[y_, True, True] :=
Max[Table[RegionDistance[Ball[{0.5, 12, 0.1}, y^i], {y^0.3, y, y^-0.8}], {i, 0.1, 1, 0.1}]];
WhatToDo2[y_, True, False] :=
NIntegrate[Exp[-x^y]*Cos[(z + x)^y], {x, 0.1, 5}, {z, 0.2, 7}];
WhatToDo2[y_, False, False] :=
Table[
{i, NIntegrate[Exp[-x^(y*i)]*Cos[(z + x)^(y*i)], {x, 0.1, 5}, {z, 0.2, 7}]},
{i, 0.1, 1, 0.1}];
WhatToDo2[y_, False, True] := ArcTan[1/y];


(Note, I changed the strings "True"/"False" to just the symbols True/False.)

• Thanks! Would it be possible to do a similar thing if instead of "True", "False" I would have some generic strings? Feb 23, 2023 at 16:53
• Yes. You could even use a condition to pattern-match on the strings. Feb 23, 2023 at 21:01

If you really want to avoid the overload, a simpler approach than the association is to just use Switch:

WhatToDo3[y_, flag1_?BooleanQ, flag2_?BooleanQ] :=
Switch[
{flag1, flag2},
{True, True}, "the Max expression goes here",
{True, False}, "one of the NIntegrate goes here",
{False, True}, "the ArcTan goes here",
{False, False}, "the other NIntegrate goes here"]


Or, using strings:

WhatToDo4[y_, flag1_String, flag2_String] :=
Switch[
{flag1, flag2},
{"True", "True"}, "the Max expression goes here",
{"True", "False"}, "one of the NIntegrate goes here",
{"False", "True"}, "the ArcTan goes here",
{"False", "False"}, "the other NIntegrate goes here",
_, "a default would go here"]