I have been trying to figure it out and I am probably very close, but I have spent 2 hours without sucess. I have the expression below

   Total[KeyValueMap[fef[#1, #2, mem] &, #1]]] &, {<|a -> b, 
   c -> d|>, <|e -> f|>}]

which produces

{geg[1, fef[a, b, mem] + fef[c, d, mem]], geg[2, fef[e, f, mem]]}

I want to have the position of the association in the list {<|a -> b, c -> d|>, <|e -> f|>} passed both to geg and fef

That is, I want the result to be

{geg[1, fef[a, b, 1, mem] + fef[c, d, 1, mem]], geg[2, fef[e, f, 2, mem]]}
  • $\begingroup$ MapIndexed[f[#[[1]], #[[2]], #2]&, Normal[assoc]]? $\endgroup$ – b3m2a1 Feb 4 at 22:46
  • $\begingroup$ @b3m2a1 I couldn't get this to work really, as it gives the position of the rule inside the association (after converting it to a list of rules), rather than the position of the association in my list of associations $\endgroup$ – ThunderBiggi Feb 4 at 23:05
  • 1
    $\begingroup$ Ah I misread the question. The shortest thing then is probably Table[KeyValueMap[f[##, i]&, assocs[[i]]], {i, Length@assocs}] $\endgroup$ – b3m2a1 Feb 4 at 23:07
  • $\begingroup$ @b3m2a1 This does indeed work and preserves the association structure (compared to your first proposal). If you were to post it as an answer, I would upvote it, but then I will need some time to decide on which to be the accepted answer $\endgroup$ – ThunderBiggi Feb 4 at 23:19
MapIndexed[Function[{v, k}, 
  geg[First[k], Total[KeyValueMap[fef[#1, #2, First[k], mem] &, v]]]],
 {<|a -> b, c -> d|>, <|e -> f|>}]

{geg[1, fef[a, b, 1, mem] + fef[c, d, 1, mem]],
geg[2, fef[e, f, 2, mem]]}

Or, slightly more readable version:

MapIndexed[Function[{v, k}, 
     Total[KeyValueMap[Function[{key, val}, fef[key, val, First[k], mem]], v]]]],
  {<| a -> b, c -> d|>, <|e -> f|>}]

same result

With a minimal change in OP's code:

MapIndexed[geg[i = First[#2], Total[KeyValueMap[fef[#1, #2, i, mem] &, #1]]] &,
   {<|a -> b, c -> d|>, <|e -> f|>}]

same result

and, without KeyValueMap:

MapIndexed[geg[i = First[#2], Total[fef[##, i, mem] & @@@ Normal[#]]] &, 
 {<|a -> b, c -> d|>, <|e -> f|>}]

same result

| improve this answer | |
  • $\begingroup$ I don't really understand how this works, can you explain it shortly (it might also be because it is past midnight here). $\endgroup$ – ThunderBiggi Feb 4 at 23:04
  • $\begingroup$ @ThunderBiggi, just used Function[{x,y}, foo[x,y]] with named slots instead of foo[#1,#2]& to avoid slots #1 and #2 in the first argument of MapIndexed and in KeyValueMap. $\endgroup$ – kglr Feb 4 at 23:30
  • $\begingroup$ Thank you, I didn't realise this is allowed $\endgroup$ – ThunderBiggi Feb 5 at 9:22

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.