Haskell: converting a list of (a, b) key-value pairs (with possibly repeated keys) to a list of (a, [b]) grouped by key

前端 未结 6 1333
遥遥无期
遥遥无期 2021-01-01 17:13

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

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 18:03

    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.

提交回复
热议问题