[Haskell-cafe] groupBy huh?

wren ng thornton wren at freegeek.org
Fri Mar 4 06:54:53 CET 2011


On 3/3/11 7:18 PM, Jacek Generowicz wrote:
> Hi Cafe,
>
> It seems that I don't understand what groupBy does.
>
> I expect it to group together elements as long as adjacent ones satisfy
> the predicate, so I would expect ALL four of the following to give one
> group of 3 and a group of 1.
>
> Prelude> :m + Data.List
> Prelude Data.List> groupBy (<) "abcb"
> ["abcb"]
> Prelude Data.List> groupBy (<) "abca"
> ["abc","a"]
> Prelude Data.List> groupBy (<) [1,2,3,2]
> [[1,2,3,2]]
> Prelude Data.List> groupBy (<) [1,2,3,1]
> [[1,2,3],[1]]
>
> What am I missing?

The behavior is that it's comparing subsequent elements to the first 
element of the current chunk. I'm not sure how often that'd be a 
desirable behavior compared to the one you and I would expect. Of 
course, the API only specifies the behavior of groupBy on equality-like 
predicates IIRC. So technically either behavior is permissible...

This should be FAQed on the documentation a bit better.

-- 
Live well,
~wren



More information about the Haskell-Cafe mailing list