Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional opposite of flatmap?

You know how flatmap takes a sequence of items and converts each one into a new subsequence, aggregating all the subsequences:

[A, B, C] -> [A1, A2, B1, B2, B3, C1]

Is there a name for the transform which does the opposite? Something like:

[A1, A2, B1, B2, B3, C1] -> [A, B, C]

The specific example that got me thinking about this was doing evaluation of mathematical expressions:

   1 * 2 + 3 * 4 + 5 + 6 * 7 * 8 
-> 2 + 12 + 5 + 6 + 336 
-> 361

Individually, the evaluation of the 6 * 7 * 8 seems like a classic reduce step, while deciding which blocks need to be reduced would need repeated takeWhile steps.

I know how to do this in the classic iterative way, keeping track of indices and all that. For most cases, I've found a nice functional replacement for most iterative patterns. Is there a name for a single operation that does this, or a simple set of operations which can be composed to create this effect?

like image 291
Li Haoyi Avatar asked Dec 26 '11 03:12

Li Haoyi


1 Answers

I think the opposite of flatmap is groupby.

$ python3
>>> from itertools import groupby
>>> groupby(['A1', 'A2', 'B1', 'B2', 'B3', 'C1'], lambda x: x[0])
like image 189
kev Avatar answered Oct 15 '22 17:10

kev