3
$\begingroup$

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.

$\endgroup$
5
$\begingroup$

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

$\endgroup$
  • 1
    $\begingroup$ In 10.1 you can also use KeyValueMap for associations, so the second definition would become f[a_Association] := KeyValueMap[someFunction, a] $\endgroup$ – Gerli Apr 8 '15 at 13:58
  • $\begingroup$ @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... $\endgroup$ – Albert Retey Apr 8 '15 at 16:02
3
$\begingroup$
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`}}
$\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.