2

The code has three places with same variable ls. So I think it would be possible to write it as a pure function.

ls = {{1, a}, {2, b}, {3, c}};
MapThread[Insert, {ls, Table[0, {Length[ls]}], Table[2, {Length[ls]}]}] 

My attempt is:

MapThread[Insert, {#, Table[0, {Length[#]}], Table[2, {Length[#]}]} & ls] 

which is not correct.

an offer can't refuse
  • 1,745
  • 12
  • 23
  • This gives some answer: MapThread[Insert, {#, Table[0, {Length[#]}], Table[2, {Length[#]}]}] &[ls] – Andrew Jan 07 '16 at 07:15
  • @Andrew can you explain why this works? why put operator there – an offer can't refuse Jan 07 '16 at 07:19
  • 2
    & @ls instead of & ls would also work. Writing & ls is like writing f ls, which in Mathematica syntax means f multiplied by ls - and you can't multiply an anonymous function with a list. – C. E. Jan 07 '16 at 07:34
  • @Pickett What about Length@(#&ls), does this contradict with what you are saying? – an offer can't refuse Jan 07 '16 at 07:39
  • 3
    Any reason you don't just use Riffle[#, 0] & /@ ls? – ciao Jan 07 '16 at 07:39
  • @buzhidao take a look at what # & ls returns and why Length is "correct". I'voting to close this question as a duplicate of common pitfals. But you may also by interested in Function Pure Function entries in documentation. – Kuba Jan 07 '16 at 07:43
  • @ciao This is powerful, I never noticed it. – an offer can't refuse Jan 07 '16 at 07:43
  • 1
    @buzhidao If you interpret me literally I guess; you can multiply an anonymous function by a list, but it doesn't make sense to do so. What you end up with is a list of values multiplied by anonymous functions, but what good is that. Use Column @@ FullForm[# & ls] to see what I mean, those expressions that you generate by multiplying ls with # & don't mean anything. – C. E. Jan 07 '16 at 07:43

1 Answers1

2
f = Thread@Riffle[Transpose@#, 0, 2] & ;

or ciao's solution

f = Map[Riffle[#, 0] &]

gives

f[ls]

{{1, 0, a}, {2, 0, b}, {3, 0, c}}

rhermans
  • 36,518
  • 4
  • 57
  • 149