I\'m a Haskell beginner. Let\'s suppose I want to write a function convertKVList that takes a flat list of key-value pairs, where some of the keys might be rep
So, my solution overuses pattern-matching because I don't actually know what functions are in the standard library.
The idea was that if the list is sorted by the keys, then you can collect your key-values as you go. To do the logic of checking whether to add to the first key-value list or create a new entry, I used patterns and guards to define the conditionals. And liberal use of cons to prepend values to a list.
And in case the original list isn't sorted, there's a sortBy.
import Data.List
import Data.Ord
ls = [(2, 1), (1, 2), (1, 4), (1, 3), (2, 3)]
addval [] (k, v)= [(k, [v])]
addval ((k1, vals) : xs) (k2, v) | k1 == k2
= ((k1, (v : vals)) : xs)
addval ls (k, v) = ((k, [v]) : ls)
convert ls = foldl addval [] (sortBy (comparing fst) ls)
Ugly code, but it avoids using Map.