5
$\begingroup$

I have two questions. Let's think the following expression.

expr = {plus, {minus, 2, 3}, {times, 1, 2}}

Q1
I want to get something like at once
INPUT:

AllHeadPositions[expr]

OUTPUT:

expr->{{1}}
minus->{{2,1}}
times->{{3,1}}


and
Q2(MAIN)
want to get elements at one list something like

INPUT

expr[[{something to specifiy minus}]]

OUTPUT

{minus,2,3}

For 1st question,I have found the way

If[Not[NumberQ[#]], {#, Position[expr, #]}, Nothing] & /@ 
 Flatten[expr]

but what to do for the second one?

$\endgroup$
5
$\begingroup$
Thread[Extract[expr, #] -> #] & Position[expr, _Symbol, Heads -> False]

{plus -> {1}, minus -> {2, 1}, times -> {3, 1}}

expr[[Position[expr, {minus, __}][[1, 1]]]]

{minus, 2, 3}

Also

First@Cases[{minus, __}]@expr

{minus, 2, 3}

| improve this answer | |
$\endgroup$
4
$\begingroup$

For the second question:

expr[[Sequence @@ Most @@ Position[expr, minus]]]

{minus, 2, 3}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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