# Turn {4, 9, {8, {5}}, {2, 3}} into {4, 9, {64, {5}}, {4, 9}} with Map

That's the input I've put

dagny[x_] := x^2;
Map[dagny, {4, 9, {8, {5}}, {2, 3}}, {2}]


Output:

{4, 9, {64, {25}}, {4, 9}}


But this not I want. I wanna {4, 9, {64, {5}}, {4, 9}}

How to Map that at a specific Level?

• As a 'pure' function, after J.M's comment: Map[If[AtomQ[#], (#^2&)[#],#] &,exp,{2}] Commented Feb 10 at 11:21

ClearAll[dagny]
dagny[x : Except[_List]] := x^2;
dagny[x_] := x

Map[dagny, {4, 9, {8, {5}}, {2, 3}}, {2}]


{4, 9, {64, {5}}, {4, 9}}

list = {4, 9, {8, {5}}, {2, 3}};

f[x_] := x^2


Using Replace

Replace[list, {{x_, y_List} :> {f @ x, y}, {x__} :> f /@ {x}}, {1}]


{4, 9, {64, {5}}, {4, 9}}

Using ReplaceAt:

p = Position[list, x_ /; AtomQ[x], {2}, Heads -> False]

(*{{3, 1}, {4, 1}, {4, 2}}*)

ReplaceAt[list, x_ :> x^2, p]

(*{4, 9, {64, {5}}, {4, 9}}*)


Or using rules and ReplaceAll:

rules = {{a_Integer, b_List} :> {a^2, b}, {a_Integer, b_Integer} :> {a, b}^2};

list /. rules

(*{4, 9, {64, {5}}, {4, 9}}*)


Or using ReplacePart:

f = #^2 &;

ReplacePart[#, Thread[p -> f@Extract[#, p]]] &@list

(*{4, 9, {64, {5}}, {4, 9}}*)


Or using MapAt:

MapAt[f@# &, list, p]

(*{4, 9, {64, {5}}, {4, 9}}*)


Do you mean this?

MapAt[dagny, {4, 9, {8, {5}}, {2, 3}}, {{3, 1}, {4}}]

• Nope. Map at a specific level. You're trying to do with the position in a list. What I want here is a a level stuff.
– kile
Commented Jan 29, 2020 at 6:16
• @kile, then you need to modify the function you're mapping: Map[If[! ListQ[#], #^2, #] &, {4, 9, {8, {5}}, {2, 3}}, {2}] Commented Jan 29, 2020 at 6:19
• @J.M. For more generality, I recommend AtomQ. Commented Jan 29, 2020 at 6:28
• @bcegkmqs23 how to achieve that with AtomQ? can u write it in the answer?
– kile
Commented Jan 29, 2020 at 6:34
• @kile, Compare and contrast: Map[If[AtomQ[#], #^2, #] &, {4, 9, {8, {5}}, {2, 3}}, {2}]. Alternatively, you could modify the definition of your function to be mapped: dagny[x_?AtomQ] := x^2; dagny[x_] := x. Commented Jan 29, 2020 at 6:41