1
$\begingroup$

Suppose that I have a list of depth $k$, and I want to apply a function $f$ to all elements at level $n$ - e.g. $f,\{\{\{a,b\},\{b,c\}\},\{\{c,d\}\}\},3\mapsto\{\{\{f(a),f(b)\},\{f(b),f(c)\}\},\{\{f(c),f(d)\}\}\}$.

Presumably this can be done with some combination of the built-ins Map, Level, Apply, and Depth, but I can't seem to get it to work. Is there a way to define a function Function[<f>,<list>,<levelspec>] which applies a function only to terms at a certain depth in a list of lists?

$\endgroup$
3
$\begingroup$

Use {n} as the level spec to apply the function only to elements at level n. If you use n as the level spec, the function is applied to elements at levels 1 thru n.

lst = {{{a, b}, {b, c}}, {{c, d}}}

Map[f, lst, {3}]

{{{f[a], f[b]}, {f[b], f[c]}}, {{f[c], f[d]}}}

Map >> Details and Options:

enter image description here

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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