`GroupBy` in haskell

Why

groupBy (>) [-5,-4,5,4,-2,-3,2,3]

rate

[[-5],[-4],[5,4,-2,-3,2,3]]

Since -3no more than 2, should this not be grouped in different ways? I expected the result to be

[[-5],[-4],[5,4,-2,-3],[2,3]]

What am I missing?

+4
source share
1 answer

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]uses the first member of the group as a reference. Therefore, if you write:

groupBy eq (x:x2:x3)

it will be - if eq x x2executed, call eq x x3to check if it belongs x3to the same group. So the calls are:

arg1 | arg2 | (>) `on` (*1)
  -5 |   -4 | False
  -4 |    5 | False
   5 |    4 | True
   5 |   -2 | True
   5 |   -3 | True
   5 |    2 | True
   5 |    3 | True

We can see this in the source codegroupBy :

groupBy                 :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy _  []           =  []
groupBy eq (x:xs)       =  (x:ys) : groupBy eq zs
                           where (ys,zs) = span (eq x) xs

As you can see, spanaccepts eq xas a predicate, and x- the first member of the group.

, , , a -> a -> Bool : (1) ; (2) ; (3) . , . , () groupBy .

: (>) `on` (*1) (>), (*1) , , Num s, .

+4

Source: https://habr.com/ru/post/1688451/


All Articles