Created
October 26, 2014 15:08
-
-
Save wouterj/92e09ded33914ee41a21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
We are sorting the array
xs
(which is the argument passed togetQuantity
using the functioncompareASC
. The functioncompareASC
is defined in the let: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
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:
Where
countQuantity
is this function: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 be0
.Then onto the mapping, we simple map the reduce method over the array returned by
groupBy
.