Which operator can be passed to one of the bend options, which will allow me to sum the element 2 of the set, grouped by element 1, into a list of tuples?
So let's say I have a list:
[ ('A', 1) , ('A', 3) , ('B', 4 ) , ('C', 10) , ('C', 1) ]
and I want to create a list:
[ ('A', 4) , ('B', 4) , ('C', 11) ]
You can see the Haskell-iized table, and therefore the actual presentation of the table is not important here; this is an approach to taking input and creating the result that interests me. I am new to Haskell and have experience in C / C ++ / C #. I have done enough tutorials to recognize the fold application here, but cannot figure out what to add.
EDIT: In case this helps someone else, here is my solution using group, foldl1 and a map inspired by ingo response:
import qualified Data.List as List mygroup :: [ (Char,Int) ] -> [ [(Char,Int)] ] mygroup = List.groupBy (\xy -> fst x == fst y) myfold :: [(Char,Int)] -> (Char,Int) myfold = foldl1 (\xy -> (fst x, snd x + snd y)) mysum :: [(Char,Int)] -> [(Char,Int)] mysum = map myfold . mygroup
At startup:
*ListSum> mysum [ ('A',1) , ('A',2) , ('B',3) , ('C',4) , ('C',5) ] [('A',3),('B',3),('C',9)]
mygroup shows how to create groups by providing an equivalence operator. It says that two members are in the same group if their first tuples are the same.
myfold shows how to sum two tuples. It uses the first tuple in the list as the initial state for the fold and forms a tuple of the result from the sum of each element of the second set.
mysum combines these two functions with a map.
I could spend a little more time on this to see if I can break the dependency on the data schema that is currently [(Char, Int)] . I think this means providing a groupBy operator and a bend operator, and it could just be an exercise in compiling groupBy, foldl1 and map. I am new to this.
Am I getting any points for not wanting? :)