Skip to main content
1 of 5
Ben Izd
  • 9.5k
  • 1
  • 15
  • 47

General solution for using diffrent heads and levels:

customMap[fn_, list_, heads_List, level_] := 
 Replace[list, Alternatives @@ (Pattern[x, Blank[#]] & /@ heads) -> fn[x], level]

customMap[(# + 3) &, {a, 3 b, {c, d}, e}, {List}, {1}]

(*Out: {a, 3 b, {3 + c, 3 + d}, e} *)

Solution 1

Using customMap:

ListMap[fn_, list_, level_] := customMap[fn, list, {List}, level]

ListMap[(# + 3) &, {a, 3 b, {c, d}, e}, {1}]

(*Out: {a, 3 b, {3 + c, 3 + d}, e} *)

Solution 2

Using Replace:

ListMap[fn_, list_, level_] := Replace[list, x_List -> fn[x], level]

ListMap[(# + 3) &, {a, 3 b, {c, d}, e}, {1}]

(*Out: {a, 3 b, {3 + c, 3 + d}, e} *)
Ben Izd
  • 9.5k
  • 1
  • 15
  • 47