5

I have to rearrange graph described by

j = {1 -> 2, 2 -> 3, 3 -> 1};

applying some function to all vertices on the right so rearrange[j] output should give me

{1 -> f[2], 2 -> f[3], 3 -> f[1]}

I guess I can use ReplaceAll, but can't guess how.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
  • 2
    Related, more general: http://mathematica.stackexchange.com/questions/5740/using-mapat-to-map-at-a-particular-depth-levelspec – Pinguin Dirk Oct 15 '13 at 10:25

5 Answers5

10

You can use MapAt function to map function on specific part of the expression

MapAt[f, {1 -> 2, 2 -> 3, 3 -> 1}, {All, 2}]
(* ==> {1 -> f[2], 2 -> f[3], 3 -> f[1]} *)

or use replacement rule

{1 -> 2, 2 -> 3, 3 -> 1} /. Rule[a_, b_] :> Rule[a, f[b]]
mmal
  • 3,508
  • 2
  • 18
  • 38
8

Anotner way,

#1 -> f[#2]& @@@ {1 -> 2, 2 -> 3, 3 -> 1}

yields:

{1 -> f[2], 2 -> f[3], 3 -> f[1]}
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
4

Here is another way:

j={1->2,2->3,3->1};
j[[All,2]]=f/@j[[All,2]];
j

{1 -> f[2], 2 -> f[3], 3 -> f[1]}

Murta
  • 26,275
  • 6
  • 76
  • 166
4

A little bit more compact method:

MapAt[f, #, 2] & /@ {1 -> 2, 2 -> 3, 3 -> 1}
{1 -> f[2], 2 -> f[3], 3 -> f[1]}
ybeltukov
  • 43,673
  • 5
  • 108
  • 212
0

For versions 10+:

Normal[f /@ Association[j]]

{1 -> f[2], 2 -> f[3], 3 -> f[1]}

Also

KeyValueMap[# -> f @ #2 &] @ Association[j]

{1 -> f[2], 2 -> f[3], 3 -> f[1]}

ReplacePart[j, {p_,-1}:>f[j[[p,-1]]]]

{1 -> f[2], 2 -> f[3], 3 -> f[1]}

kglr
  • 394,356
  • 18
  • 477
  • 896