0
$\begingroup$

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?

$\endgroup$

3 Answers 3

2
$\begingroup$

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

$\endgroup$
2
$\begingroup$

You could just overload WhatToDo:

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.)

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

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"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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