2
$\begingroup$

Let's say I've got a list of procedures:

{Print[1];, Print[2];, Print[3];}

And I want to only evaluate 3rd one:

{Print[1];, Print[2];, Print[3];}[[3]]
1... 2... 3...

Well, that's not what I've wanted, the walkaround would be to use Hold:

Hold[{Print[1];, Print[2];, Print[3];}][[ 1, 3]]
3

My question is: is there more "proper" way to do this?

p.s. the most tidy what I thought of is Switch:

Switch[2,
 1, Print[1],
 2, Print[2],
 3, Print[3] ]
2
$\endgroup$
1
  • 1
    $\begingroup$ Since Part doesn't have attribute HoldAll, you either 1) wrap the commands in Hold or Unevaluated, 2) redefine Part, or 3) add via UpSet a new definition to Part to handle held input (wrapped in e.g. hold) differently. $\endgroup$ Dec 13, 2013 at 8:06

1 Answer 1

1
$\begingroup$

You can define a new function with attribute HoldAll, but I don't think you can avoid using Unevaluated or Hold.

Attributes[holdChoice] = {HoldAll};
holdChoice[cases__, n_] := (Unevaluated@{cases})[[n]];

holdChoice[Print[1]; 11, Print[2]; 22, Print[3]; 33, 2]
During evaluation of In[21]:= 2

Out[23]= 22
$\endgroup$
1
  • $\begingroup$ Yes, I was aware of the Attributes. This is the way too. I'm just thinking if I don't miss anything. I mean, I want to avoid reinventing the solution which might be there. Switch seems to be ok but there is unecessary 1, 2... for each case :) too much work ;P $\endgroup$
    – Kuba
    Dec 13, 2013 at 8:21

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.