How to extract arguments of functions in an expression? [duplicate]

This question already has an answer here:

How to completely delete the head of a function expression

6 answers

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]

=================

=================

3 Answers
3

=================

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:

How to completely delete the head of a function expression

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.

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.