3
$\begingroup$

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.

$\endgroup$
6
$\begingroup$

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}

$\endgroup$
  • 1
    $\begingroup$ It works until I do something stupid like c = 2; a = 2; w = 2; $\endgroup$ – Dr. belisarius Nov 21 '14 at 5:01
  • $\begingroup$ 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. $\endgroup$ – SquareOne Nov 21 '14 at 11:43
  • $\begingroup$ @belisarius Actually it suffices that c=a. $\endgroup$ – SquareOne Nov 21 '14 at 11:45
9
$\begingroup$
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*)
$\endgroup$
  • $\begingroup$ +1. One can also use strings, "a", "b", etc., if longer, more descriptive names are desirable, such "cat". $\endgroup$ – Michael E2 Nov 21 '14 at 15:02
  • 1
    $\begingroup$ @MichaelE2 Or a formal cat $\endgroup$ – Dr. belisarius Nov 21 '14 at 15:25
2
$\begingroup$

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"].

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