[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Write this accumuator in a functional style

Steven D'Aprano wrote:

> I have a colleague who is allergic to mutating data structures. Yeah, I
> know, he needs to just HTFU but I thought I'd humour him.
> Suppose I have an iterator that yields named tuples:
> Parrot(colour='blue', species='Norwegian', status='tired and shagged out')
> and I want to collect them by colour:
> accumulator = {'blue': [], 'green': [], 'red': []}
> for parrot in parrots:
>     accumulator[parrot.colour].append(parrot)
> That's pretty compact and understandable, but it require mutating a bunch
> of pre-allocated lists inside an accumulator. Can we re-write this in a
> functional style?
> The obvious answer is "put it inside a function, then pretend it works by
> magic" but my colleague's reply to that is "Yes, but I'll know that its
> actually doing mutation inside the function".
> Help me humour my colleague.

Wouldn't it be on your colleague to provide a competetive "functional" 

However, reusing Gregory's sample data:

>>> def color(p): return p.color
>>> {c: list(ps) for c, ps in groupby(
...  sorted(parrot_generator(), key=color), key=color)}
{'red': [Hawaiian/red/laid back], 'blue': [Norwegian/blue/tired and shagged 
out, Norwegian/blue/dead, French/blue/tres bon], 'green': 
[Portugese/green/perky, Italian/green/excited]}