pyrsistent icon indicating copy to clipboard operation
pyrsistent copied to clipboard

Add new key based on other elements

Open Drvanon opened this issue 2 years ago • 3 comments

It might be that I am misunderstanding the point of transform, but I want to do pasically the following transformation: [{"upper":"A"}, {"upper":"B"}] -> [{"upper":"A", "lower":'a'}, {"upper":"B", "lower":'b'}]

I would have expected to be able to do this as follows: freeze([{"upper":"A"}, {"upper":"B"}]).transform([ny, 'lower'], lambda pmap: string.lower(pmap.upper)), but this not work, clearly. Is there any particular way to achieve that other than using evolver and iterating over the indexes?

Drvanon avatar Jul 26 '22 07:07 Drvanon

Alright, clearly I was struggling with the whole FP concept again. The usual way of solving this is using a map, like so:

my_vec = freeze([{"upper":"A"}, {"upper":"B"}])
lowered_vec = pvector(map(lambda pmap: pmap.set("lower", pmap.upper.lower())))

I find I am doing this a lot. From rust I am used to calling .map as an attribute to iterators, maybe that would be a nice interface here as well, replacing the annoying pvector(map()) combo? Suggested implementation:

class PVector:
    ...
    def map(self, func):
        return pvector(map(func, self))

Drvanon avatar Jul 27 '22 04:07 Drvanon

Would that solve your problem?

my_vec = freeze([{"upper":"A"}, {"upper":"B"}])
my_vec.transform([ny], lambda pmap: pmap.set("lower", pmap.upper.lower()))

that gives me, what you want:

pvector([pmap({'upper': 'A', 'lower': 'a'}), pmap({'upper': 'B', 'lower': 'b'})])

and it works not just on the highest level as map does. Works for a list somewhere in a highly nested pvector/pmap structure.

horvatha avatar Aug 04 '22 05:08 horvatha

I think I should've linked you @Drvanon . I think that transpose is more general than map, and it work with your use case, but you need to use one less level as the first parameter, that gives you the dictionary, and you can do with it whatever you want.

horvatha avatar Aug 06 '22 13:08 horvatha

Hey, sorry i did not get an email on this one so it took me a while to respond. This does indeed solve my problem. I think I still had to get used to some of the ideas of immutability in nested generic objects first. Thanks for your feedback!

Drvanon avatar Sep 01 '22 23:09 Drvanon