4

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.

Michael E2
  • 235,386
  • 17
  • 334
  • 747
Pam
  • 1,867
  • 11
  • 24

2 Answers2

8

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
]
Teake Nutma
  • 5,981
  • 1
  • 25
  • 49
3

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}}
RunnyKine
  • 33,088
  • 3
  • 109
  • 176
  • +1 Nice to hear indeed. I wonder if this is in fact based upon @LeonidShifrin's LetL. – Teake Nutma Jul 17 '14 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 '14 at 11:46
  • Thanks… I haven’t upgraded to MMA 10… but this is great…. – Pam Jul 17 '14 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 '14 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 '14 at 14:21