6
$\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$

4 Answers 4

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}

$\endgroup$
4
$\begingroup$

For the second question:

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

{minus, 2, 3}

$\endgroup$
1
$\begingroup$
expr = {plus, {minus, 2, 3}, {times, 1, 2}};

Question 1

Transpose[{
  Replace[expr, {a_, __} :> a, {1}],
  Position[expr, _Symbol, Heads -> False]}]

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

Question 2

First@ Extract[Position[expr, {minus, __}]] @ expr

{minus, 2, 3}

$\endgroup$
1
$\begingroup$
expr = {plus, {minus, 2, 3}, {times, 1, 2}};

Question 1: Using SequecenCases and Position.

patt = s : {_Symbol} :> Splice /@ {s, Position[#, s[[1]]]} &;

SequenceCases[Flatten@#, patt@#] &@expr 

(*{{plus, {1}}, {minus, {2, 1}}, {times, {3, 1}}}*)

Question 2: Using SequencePosition.

#[[First @@ SequencePosition[Flatten@#, {minus}]]] &@expr

(*{minus, 2, 3}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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