4
$\begingroup$

I was trying to make a simple question but made it trivial. So the original setting is as follows:

expr = {{a}, b, {{c}, {e}}, d, {}}

I need that all lists are with f head (except outermost, including nested):

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

What kind of pattern should I use with /. in this case? (I do not need MapAt or something that works with positions or levels).

I've tried

expr /. x : ({___List} | {_}) :> f@x

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

Lists {c} and {e} left unattended, inspite of the fact that expr /. x : {_} :> f@x works with them. Some explanation of what am I doing wrong is welcome.

Thank you in advance. Excuse me those who had to read previuos version.

$\endgroup$
5
  • 4
    $\begingroup$ Replace[expr, x_List :> f[x], {1, \[Infinity]}] ? $\endgroup$ – user31159 Jan 17 '16 at 21:55
  • $\begingroup$ @Xavier, yes, thank you, that is fine. Can you add the version with ReplaceAll? $\endgroup$ – garej Jan 17 '16 at 21:59
  • $\begingroup$ @Xavier, you are right about Algohi's post but your solution (deleted) also deserves attention. Do not hide it, I've learned from it, it also might be useful for other people. $\endgroup$ – garej Jan 17 '16 at 22:43
  • $\begingroup$ @garej Xavier has chosen Replace instead of ReplaceAll quite deliberately because Replace gives you control over which levels of the expression are subject to replacement, whereas ReplaceAll does not. This control is needed here. Xavier's solution would be mine as well. $\endgroup$ – Oleksandr R. Jan 17 '16 at 23:29
  • $\begingroup$ @OleksandrR., you are in general right. Nonetheless, my aim here was to understand patterns better, not only to solve the very class of problems. By the way, Xavier suggested a couple of workarounds that later decided to remove. That is pity for me. $\endgroup$ – garej Jan 18 '16 at 6:09
6
$\begingroup$
(expr /. List :> Composition[f, List])[[1]]
(*{f[{a}], b, f[{f[{c}], f[{e}]}], d, f[{}]}*)
$\endgroup$
1
2
$\begingroup$
expr /. x : {_} | {} :> f[x] /. x : {__f} :> f[x]

enter image description here

$\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.