0
$\begingroup$

I would like to recover a subexpression from its position in the expression.

For instance:

 Position[{3, {3, 5, {6}}}, 6]

returns the position of 6 in the list, namely:

 {{2, 3, 1}}

to recover the list element 6 from the position {{2,3,1}} we can use;

 {3, {3, 5, {6}}}[[2]][[3]][[1]]

which returns

 6

However, I want to apply {3, {3, 5, {6}}} in one go, rather than repeatedly applying it, first to [[2]], then to [[3]] and finally to [[1]].

It seems that I need something close to FoldList which would apply expr[[#]] & repeatedly to elements of list consisting of the flattened position, where the position indicates a subexpression in expr.

I am not sure if this plan is workable.

It seems such a natural operation to recover a subexpression based on its position. Is there a Mathematica defined function for this?

$\endgroup$
  • 3
    $\begingroup$ That's precisely what Extract is made for. $\endgroup$ – Henrik Schumacher Jul 24 '19 at 3:59
  • 1
    $\begingroup$ you can also do: {3, {3, 5, {6}}}[[##]] & @@@ Position[{3, {3, 5, {6}}}, 6] $\endgroup$ – kglr Jul 24 '19 at 4:04
  • $\begingroup$ Thanks both, that works. I'd like to select reply 1 by Henrik as the answer and learned from kglr's observation. Forgot you could access matters also as: {3, {3, 5, {6}}}[[2, 3, 1]] rather than {3, {3, 5, {6}}}[[2]][[3]][[1]] $\endgroup$ – Mike Jul 24 '19 at 4:31
  • 1
    $\begingroup$ See also Position, "Details and Options," second bullet point. $\endgroup$ – Michael E2 Jul 24 '19 at 5:00
  • 1
    $\begingroup$ Look at the first example under "Properties and Relations," which is a natural place to look to see how the function being looked up (Position) relates to other functions. $\endgroup$ – Michael E2 Jul 24 '19 at 5:17