Haskell: surprising behavior of “groupBy”

后端 未结 4 1040
無奈伤痛
無奈伤痛 2020-12-30 04:07

I\'m trying to figure out the behavior of the library function groupBy (from Data.List), which purports to group elements of a list by an \"equality test\" function passed i

4条回答
  •  天命终不由人
    2020-12-30 04:54

    The fact that "<" isn't an equality test.

    You might expect some behavior because you'd implement it differently, but that isn't what it promises.

    An example of why what it outputs is a reasonable answer is if it sweeps through it, doing

    [1, 2, 3, 2, 4, 1, 5, 9] ->
    [[1,2,3], [2,4], [1,5,9]]
    

    Now has 3 groups of equal elements. So it checks if any of them are in fact the same:

    Since it knows all elements in each group is equal, it can just look at the first element in each, 1, 2 and 1.

    1 > 2? Yes! So it merges the first two groups.

    1 > 1? No! So it leaves the last group be.

    And now it's compared all elements for equality.

    ...only, you didn't pass it the kind of function it expected.

    In short, when it wants an equality test, give it an equality test.

提交回复
热议问题