Skip to content

Instantly share code, notes, and snippets.

@wouterj
Created October 26, 2014 15:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wouterj/92e09ded33914ee41a21 to your computer and use it in GitHub Desktop.
Save wouterj/92e09ded33914ee41a21 to your computer and use it in GitHub Desktop.
import Data.List (groupBy, sortBy)
getQuantity xs = let countQuantity acc (_, "registered") = succ acc
countQuantity acc (_, "sold") = pred acc
compareASC (i1, _) (i2, _)
| i1 < i2 = LT
| i1 > i2 = GT
| i1 == i2 = EQ
in map (foldl (countQuantity) 0) $ groupBy (\x y -> (fst x) == (fst y)) $ sortBy (compareASC) xs
-- example usage
-- getQuantity [(1, "registered"), (1, "sold"), (2, "registered"), (1, "registered"), (2, "sold"), (1, "registered")]
-- >> [2, 0]
@wouterj
Copy link
Author

wouterj commented Oct 26, 2014

The input

The input is a list of puples. The puples are constructed like (id, event). E.g. (1, "registered") means product type 1 is registered 1 time.
#1. Sorting

sortBy (compareASC) xs

We are sorting the array xs (which is the argument passed to getQuantity using the function compareASC. The function compareASC is defined in the let:

compareASC (i1, _) (i2, _)
  | i1 < i2  = LT
  | i1 > i2  = GT
  | i1 == i2 = EQ

On line 1, we say that we only want to get the first items of both tuples: the ids. Then we compare the ids using a simple compare function, which is just a normal ASC sorting function.

This means the tuples are sorted by their ID ASC.
#2. Grouping

groupBy (\x y -> (fst x) == (fst y)) ...

Here we are grouping ... (the sorted array from (1)). We group by the first element of the tuple (fst x gives you the first item). This means we group everything with the same ID.
We had to sort first, since grouping works recursively (like everything else) in haskell. That means that once we created a new list, we can't add elements to the previous list. So [(1, "registered"), (2, "registered"), (1, "sold")] would let to no grouping of ID 1. With sorting, this becomes [(1, "registered"), (1, "sold"), (2, "registered")] which can be grouped into [[(1, "registered"), (1, "sold")], [(2, "registered")]]
#3. Map reduce

Then we need to map over each grouped list to reduce it to a number. Let's first take a look at the reduce:

foldl (countQuantity) 0

Where countQuantity is this function:

countQuantity acc (_, "registered") = succ acc
countQuantity acc (_, "sold")       = pred acc

Here we are argument matching, if the second element of the tuple is "registered", we take the successor (++ in PHP) of acc (the carry) and when it's "sold" we take the pred (-- in PHP) of acc. We define the starting value to be 0.

Then onto the mapping, we simple map the reduce method over the array returned by groupBy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment