Each output of the resulting list is a tuple of two components: A representative element of the group (e.g.
's') and the group itself (e.g.
Data.List produces a list of the groups.
Its output does not also include a representative element of the group as Python’s does, but if this is desired then it can be recovered by taking the
head of each group.
This is a situation where composing the two functions
using the function composition operator,
(.), might read more nicely.
Let’s say we have a function that categorizes characters into one of three varieties:
If we use this
character_class function as the
groupby, then the grouping is now performed not based on whether elements are the same, but based on whether elements belong to the same character class.
The first element of each tuple (
k in the example above) now tells us which class the characters in the group belong to. The second element gives the characters themselves.
Now again in Haskell! First we’ll define an equivalent of the
character_class function using Haskell’s guard syntax:
We can use the
groupBy function for this.
Data.List Its first argument serves a purpose similar to that of the
key parameter, but instead of a unary function that produces a key, we need to give it a binary function that determines whether two elements belong to the same group.
We want two elements to end up in the same group if they have the same character class, so the function we need to use is
So our grouping then looks like this:
We can write this a bit more concisely using the
The purpose of the
on function is to be used exactly like this, and the idea behind its name is that the expression reads a bit like an English phrase:
This does not, however, give us the value of the key for each group like the Python function did; it only does the grouping, it doesn’t tell us which character class each group belongs to. If we want that, we have to write our own function. The implementation we give below uses three steps:
groupByto group the list according to the key
fst (head xs): The key of the first item in the group; (It doesn’t matter which item we look at, since the group values all have the same key)
map snd xs: The values in the group.