When I try to Thread
Part
function over two nested arrays, the operation is performed as expected but i get a warning. I'm not sure if (and what) am I doing wrong. The code example is below.
lst1 = {{5, -9, 15}, {12, -15, 4}}
indices={{2,1,3},{1,3,2}}
Thread[Part[lst1,indices]]
and the output is
{{-9, 5, 15}, {12, 4, -15}}
as expected. However, the following warning was thrown.
Part::pkspec1: The expression {{2,1,3},{1,3,2}} cannot be used as a part specification. >>
Shouldn't Part
be threaded over the list as described in the help under Thread
function?
Answer
RunnyKine already explained in detail the source of the message. I would like to offer a couple of alternative formulations of a solution and comment on your attempt to use Hold
.
You commented:
I tried
Thread[Hold[Part[lst1,indices]]]//ReleaseHold
. Apparently placedHold
at wrong place.
Indeed, for two reasons.
In this expression
Hold
is the active head of the argument ofThread
so, if it were possible, it is the head that would be distributed:Thread[Hold[{1, 2, 3}]]
{Hold[1], Hold[2], Hold[3]}
For
Thread
to operate it must see explicit arguments at second level of the expression.Hold
here preventslst1
andindices
from evaluating to their full forms therefore even if (1) is solved a problem remains. To illustrate this we can useUnevaluated
which is like a temporaryHold
that prevents evaluation but is transparent to the function in which it appears, i.e.Thread
:Thread[Unevaluated[Part[lst1, indices]]] (* Part::pkspec1 printed *)
RunnyKine's use of Inactive
and andre's use of Hold[Part]
each get around both these problems because:
They do not introduce an additional level in the expression;
Hold[Part]
is a compound head.TreeForm /@ {Hold[head[1, 2]], Hold[head][1, 2]}
While
Part
is rendered inactive the arguments of the compound head still evaluate in the default manner thereforelst1
andindices
are expanded.
Another way to temporarily inactivate Part
is Block
:
Block[{Part}, Thread @ lst1[[indices]] ]
But as already demonstrated by ciao (rasher) this kind of inhibition is not needed as MapThread
allows exactly the evaluation you want: expansion of lst1
and indices
before Part
is applied and evaluated.
Comments
Post a Comment