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.

This question is related to:

Composition of functions using slots

`Slot` (#) interfering with evaluation

Consider a toy example:

 list1 = { {a1, b1, c1, d1}, {a2, b2, c2, d2}, {a3, b3, c3, d3} };

I’d like to take elements from the list as follows example:

{#1, #2}@@@ list1

But I’d like to able to define #1, #2 programmatically.

I tried:

n=1;
{Slot@Evaluate[n], Slot@Evaluate[n + 1]} & @@@ list1

But it gives me an error…

Answers appreciated.Even better if the answer uses the # notation rather than the Slot function.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

You can use With to insert values into held expressions:

With[{n=1,m=2},
  {Slot[n], Slot[m]} & @@@ list1
]

{{a1, b1}, {a2, b2}, {a3, b3}}

If you're so inclined, you can do a nested With:

With[{n = 1},
 With[{m = n + 1},
  {Slot[n], Slot[m]} & @@@ list1
 ]
]

Or with Leonid's exceedingly nice LetL:

LetL[{n = 1, m = n + 1},
  {Slot[n], Slot[m]} & @@@ list1
]
share|improve this answer
    
oh. I was too late! –  acl Jul 17 at 11:34
    
@acl Sorry, I cheated a bit by first posting half of my answer. Too bad you removed yours, as I wasn't aware that With[{n = n},...] was also allowed. –  Teake Nutma Jul 17 at 11:41
    
+1. You can also use Where in V10 see my answer. –  RunnyKine Jul 17 at 11:43
    
That's a very useful trick. Why don't you add it to your answer? –  acl Jul 17 at 11:57

There's a nice function in the GeneralUtilities package included in Version 10 called Where. You can use this as:

Needs["GeneralUtilities`"]

Where[n = 1, m = n + 1, {Slot[n], Slot[m]} & @@@ list1]

Gives:

{{a1, b1}, {a2, b2}, {a3, b3}}
share|improve this answer
    
+1 Nice to hear indeed. I wonder if this is in fact based upon @LeonidShifrin's LetL. –  Teake Nutma Jul 17 at 11:44
    
@TeakeNutma I wonder too. I just hope it is added as an internal function in a future release as I always use such functionality. –  RunnyKine Jul 17 at 11:46
    
Thanks… I haven’t upgraded to MMA 10… but this is great…. –  Pam Jul 17 at 11:52
    
@TeakeNutma AFAIK its not. LetL also supports shared local variables in definitions, as well as macro-expands at definition time, which makes it zero overhead w.r.t. manually-written nested With in function definitions (these are related). Again AFAIK, Where does not have this functionality. –  Leonid Shifrin Jul 17 at 13:59
1  
Where seems to have a definition intended to catch things like Where[{x,y}={2, 3}, f[x,y]] that they added last and is never tried. To fix it, use DownValues[Where] = RotateRight@DownValues@Where –  Rojo Jul 24 at 14:21

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.