5
$\begingroup$

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.

$\endgroup$
1
10
$\begingroup$

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]]
$\endgroup$
8
$\begingroup$

Anotner way,

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

yields:

{1 -> f[2], 2 -> f[3], 3 -> f[1]}
$\endgroup$
2
  • 1
    $\begingroup$ I think that brackets are unnecessary. Just #1 -> f[#2] & @@@. $\endgroup$
    – ybeltukov
    Oct 15 '13 at 10:15
  • $\begingroup$ Yes! sorry...silly mistake...have corrected $\endgroup$
    – ubpdqn
    Oct 15 '13 at 11:10
4
$\begingroup$

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]}

$\endgroup$
4
$\begingroup$

A little bit more compact method:

MapAt[f, #, 2] & /@ {1 -> 2, 2 -> 3, 3 -> 1}
{1 -> f[2], 2 -> f[3], 3 -> f[1]}
$\endgroup$
0
$\begingroup$

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]}

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