1
$\begingroup$

Input Code

a[1]=UnitVector[4,1]
b[1]=1

Now I want replace the head of b[1] by a, something similar to

a@@b[1]

The result above is 1, however, I want to get the result {1,0,0,0}

How can I do that?

$\endgroup$
  • $\begingroup$ f @@@ Hold[g[1]] // ReleaseHold do some reading on evaluation (specifically this). It'll help a lot. $\endgroup$ – b3m2a1 Jul 29 '17 at 3:36
4
$\begingroup$

What's happening is that a@@b[1] evaluates to Apply[a, b[1]], which to evaluates to Apply[a, 1]. This is standard evaluation; there is nothing that prevents b[1] from evaluating inside Apply[a, b[1]]. Hold[b[1]] prevents b[1] from evaluating, i.e.

Apply[a, Hold[b[1]], {1}]

Hold[a[1]]

You can then apply ReleaseHold to remove Hold and evaluate a[1]. We can also create a function which has the HoldAll attribute, meaning that it won't evaluate its arguments like Apply does.

SetAttributes[replaceHead, HoldAll]
replaceHead[_[args___], h_] := h[args]
replaceHead[b[1], a]

{1, 0, 0, 0}

The HoldAll attribute means that replaceHead[b[1], a] is not replaced by replaceHead[1, a] as it would normally be.

$\endgroup$
2
$\begingroup$

You can use Unevaluated to apply the head to the input expression:

In[139]:= Apply[a, Unevaluated[b[1]]]
Out[139]= {1, 0, 0, 0}
$\endgroup$

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