13
$\begingroup$

Say I have some nested structure, such as {a,{{b,c},d,{e,{f,g}}}}, and I want to apply a function $q$ to each of the leaves; that is, I want the output to be {q[a],{{q[b],q[c]},q[d],{q[e],{q[f],q[g]}}}}. There must be a primitive to do this, but I can't find it. I initially thought that Map with a third argument of Infinity would do it, but that does something different (in addition to applying q at the leaves, it also applies it to each higher-level list element).

$\endgroup$
  • 4
    $\begingroup$ Attributes[q] = Listable or you can Map at {-1} unless a,b,c... are non atomic, $\endgroup$ – Kuba Nov 16 '15 at 14:53
  • $\begingroup$ @Kuba I guess I should have read that page more carefully. Thanks. $\endgroup$ – rogerl Nov 16 '15 at 14:56
  • $\begingroup$ @Kuba I should note that the Attributes[q] = Listable version won't work unless all containers for leaves are Lists. $\endgroup$ – Leonid Shifrin Nov 16 '15 at 15:53
16
$\begingroup$

A little "secret" of level specifications is that they can be negative. -1 refers to the atomic leaves, -2 refers to all Depth 2 subexpressions, generally -k refers to all depth k subexpressions. Thus the behaviour of negative levels is somewhat different from that of positive ones.

You can read more here:

Mapping at level {-1} (i.e. only level -1, not a range of levels) will accomplish what you need.

Level[{a, {{b, c}, d, {e, {f, g}}}}, {-1}]
(* {a, b, c, d, e, f, g} *)

Map[x, {a, {{b, c}, d, {e, {f, g}}}}, {-1}]
(* {x[a], {{x[b], x[c]}, x[d], {x[e], {x[f], x[g]}}}} *)
$\endgroup$
  • 1
    $\begingroup$ This reminds me of Bob Ross [badly paraphrased]: "...just happy little secrets..." $\endgroup$ – Yves Klett Nov 16 '15 at 15:09
  • 1
    $\begingroup$ Worth linking: Levels: how do they work? $\endgroup$ – Kuba Nov 16 '15 at 15:31
  • $\begingroup$ @Kuba Thanks! I knew there had to be such a post, but couldn't find the right one. I wasn't familiar with this specific question you linked, but it seems to be the best one. $\endgroup$ – Szabolcs Nov 16 '15 at 15:47

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.