How to make function accept list of rules as an argument?

Considering the list of rules:

r= {“a” -> “1”, “b” -> “2”, “c” -> 3, d -> 231, “e” -> 1.25};

I want to have a function f[…_] := SomeFunction(key, value) so that I can give r to f: f[r] and will do SomeFunction(key, value) on all elements of r.

p.s. Same question stands for Association.

Any idea?
Thanks.

=================

=================

2 Answers
2

=================

this would be a definition which does what you want for a list of rules:

f[r : {__Rule}] := someFunction @@@ r

and this would be one which handles the Association case:

f[a_Association] := someFunction @@@ Normal[a]

As mentioned by Gerli in a comment in version 10.1 one can also use KeyValueMap for the second case, for which that new function was added:

f[a_Association] := KeyValueMap[someFunction,a]

both assume that you want to return a list of returnvalues of someFunction…

1

 

In 10.1 you can also use KeyValueMap for associations, so the second definition would become f[a_Association] := KeyValueMap[someFunction, a]
– Gerli
Apr 8 ’15 at 13:58

  

 

@Gerli: good point, I somehow had in mind that I had seen this, but as I only have 10.0.2 installed I couldn’t find it and I did not bother to search more. I have added it in my answer, thanks for pointing that out…
– Albert Retey
Apr 8 ’15 at 16:02

r = {“a” -> “1”, “b” -> “2”, “c” -> 3, d -> 231, “e” -> 1.25};
someFunction[key_, value_] := {key, value}; (* say *)

f = someFunction @@@ # &
f@r
{{“a”, “1”}, {“b”, “2”}, {“c”, 3}, {d, 231}, {“e”, 1.25`}}