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]
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]
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:
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.