# How to select the value of a substitution rule for a particular variable?

Say I have the following lists of rules:

case1 = {a -> 1, b -> 3, c -> 4, e -> 5}
case2 = {c -> 3, a -> 1, w -> 2}
case3 = {x -> 5, y -> 2, z -> 0, c -> 2}


How do I write a function myfun[], to select the value of "c" in each case?

I want

myfun[case1]


to return 4;

myfun[case2]


to return 3;

myfun[case3]


to return 2.

An alternative to @belisarius' use of formal symbols to overcome the problem caused by c having been assigned a value

case1 = {a -> 1, b -> 3, c -> 4, e -> 5};
case2 = {c -> 3, a -> 1, w -> 2};
case3 = {x -> 5, y -> 2, z -> 0, c -> 2};

myfun[x_] := Cases[x, (c -> val_) :> val][[1]]

myfun /@ {case1, case2, case3}


{4, 3, 2}

c = 5;

myfun /@ {case1, case2, case3}


{4, 3, 2}

• It works until I do something stupid like c = 2; a = 2; w = 2; – Dr. belisarius Nov 21 '14 at 5:01
• Actually, there is no difference between this solution and belisarius's c/.x. It is not solving the problem with c having an assigned value. – SquareOne Nov 21 '14 at 11:43
• @belisarius Actually it suffices that c=a. – SquareOne Nov 21 '14 at 11:45
myfun[x_] := c /. x
myfun /@ {case1, case2, case3}
(* {4, 3, 2} *)


But please note that if you inadvertently assign a value to the symbol c, it goes astray and can't be repaired by tricks done only on myfun[] since it "corrupts" your cases lists.
Considering the above, perhaps it is safer to work with Formal symbols if you really need this kind of construct.

case1F = {\[FormalA] -> 1, \[FormalB] -> 3, \[FormalC] ->  4, \[FormalE] -> 5};
myfun1[x_] := \[FormalC] /. x
myfun1[case1F]
(*4*)

• +1. One can also use strings, "a", "b", etc., if longer, more descriptive names are desirable, such "cat". – Michael E2 Nov 21 '14 at 15:02
• @MichaelE2 Or a formal cat – Dr. belisarius Nov 21 '14 at 15:25

In such a case, with Mathematica 10, one can use easily associations:

case1 = {a -> 1, b -> 3, c -> 4, e -> 5}
case2 = {c -> 3, a -> 1, w -> 2}
case3 = {x -> 5, y -> 2, z -> 0, c -> 2}


then:

ac1 = Association@case1;
ac2 = Association@case2;
ac3 = Association@case3


The associated value for the key "c" one gets in the following way:

 ac2[Key[c]]


the associated value 3. The whole thing is more easy when the keys are strings, in this case you can simply write ac2["c"].