3
$\begingroup$

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]

$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$
    – Mr.Wizard
    Oct 29, 2014 at 21:09

3 Answers 3

6
$\begingroup$

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:

$\endgroup$
4
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ This is far more elegant and idiomatic than any solution I've seen on this site +1. $\endgroup$
    – alessandro
    Nov 29, 2020 at 15:39
1
$\begingroup$

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.

$\endgroup$

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