Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
share|improve this question
1  
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. –  István Zachar Dec 13 '13 at 8:06
add comment

1 Answer

up vote 1 down vote accepted

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
share|improve this answer
    
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 –  Kuba Dec 13 '13 at 8:21
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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