4
$\begingroup$

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?

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

4 Answers 4

4
$\begingroup$
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}}

$\endgroup$
2
$\begingroup$
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}}

$\endgroup$
2
$\begingroup$

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}}*)
$\endgroup$
0
$\begingroup$

Do you mean this?

MapAt[dagny, {4, 9, {8, {5}}, {2, 3}}, {{3, 1}, {4}}]
$\endgroup$
5
  • $\begingroup$ 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. $\endgroup$
    – kile
    Commented Jan 29, 2020 at 6:16
  • 1
    $\begingroup$ @kile, then you need to modify the function you're mapping: Map[If[! ListQ[#], #^2, #] &, {4, 9, {8, {5}}, {2, 3}}, {2}] $\endgroup$ Commented Jan 29, 2020 at 6:19
  • 1
    $\begingroup$ @J.M. For more generality, I recommend AtomQ. $\endgroup$
    – bcegkmqs23
    Commented Jan 29, 2020 at 6:28
  • $\begingroup$ @bcegkmqs23 how to achieve that with AtomQ? can u write it in the answer? $\endgroup$
    – kile
    Commented Jan 29, 2020 at 6:34
  • 1
    $\begingroup$ @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. $\endgroup$ Commented Jan 29, 2020 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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