3

How can I extract the argument of a function in an expression?

expr=b[c];

I need some f[expr] that will return c.

d[f[expr]] -> d[c]

Jerry Guern
  • 4,602
  • 18
  • 47
  • On reflection I think that this question, if no additional detail is added, can be closed as a duplicate of (50381) since all methods below are given there and with greater detail. – Mr.Wizard Oct 29 '14 at 21:09

3 Answers3

6

Using patterns for destructuring:

expr = b[c];

f[_[x__]] := x

d[f[expr]]
d[c]

Or more directly with Apply:

d @@ expr
d[c]

Both forms also works with multiple arguments:

 d[ f[ p[1, 2, 3] ] ]
d[1, 2, 3]
d @@ p[1, 2, 3]
d[1, 2, 3]

Also see:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
4

Your example is a little unclear to me but if you're asking for a list of the arguments then

List @@ expr

does the job. This is the short form of Apply[List, expr] it simply replaces the head of expr, in your example b, by List.

MikeLimaOscar
  • 3,456
  • 17
  • 29
1

The following code does this:

f[e_] := e[[1]]

This works because all expressions have the same internal form, head[arg1, ..., argn] and e[[1]] really just accesses the first argument, arg1, without caring for the head.. Since {a, b, c} is just syntactic sugar for List[a, b, c], also {a,b,c}[[1]] returns a.

celtschk
  • 19,133
  • 1
  • 51
  • 106