Is there any way to completely remove the head of an expression function?
For example, how would I remove the head Cos
from Cos[a]
to give only a
as an output.
Answer
You can actually Delete
the head of the expression, which is part 0
:
Delete[#, 0] & /@ {Cos[a], Sin[b], Tan[c]}
{a, b, c}
With version 10 operator forms:
Delete[0] /@ {Cos[a], Sin[b], Tan[c]}
{a, b, c}
One case of interest may be held expressions. If our expression is:
expr = HoldComplete[2 + 2];
And the head we wish to remove is Plus
, we cannot use these:
Identity @@@ expr
Sequence @@@ expr
expr /. Plus -> Identity
expr /. Plus -> Sequence
Replace[expr, _[x__] :> x, 1]
All produce e.g.:
HoldComplete[Identity[2, 2]] (* or Sequence *)
We can use Delete
or FlattenAt
:
Delete[expr, {1, 0}]
FlattenAt[expr, 1]
HoldComplete[2, 2]
HoldComplete[2, 2]
You could also use a pattern that includes the surrounding expression on the right-hand-side, as demonstrated here, e.g.:
expr /. h_[_[x__]] :> h[x]
HoldComplete[2, 2]
Notes
As the documentation for Delete
reads:
Deleting the head of a whole expression makes the head be Sequence.
Delete[Cos[a], 0]
Sequence[a]
Since this resolves to a
in normal evaluation this should usually not be an issue.
Comments
Post a Comment