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

前端 未结 6 1310
遥遥无期
遥遥无期 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 17:59

    One of the most important points when writing a function, is trying to split what it should do into separate sub-tasks (which are often put together by function composition in the end). E.g., in the definition you came up with, there are three tasks (in order of application, i.e., from right to left in the definition):

    1. map the 2nd component of each pair to a singleton list (thereby enabling the use of Map.fromListWith)
    2. create a map (which takes care of merging entries with equal keys)
    3. turn it into a list

    I wanted to post a different solution (which was an exact copy of the code Mark posted in the meanwhile ;)). Just to make clear that most of the time there are different routes to the same goal. In his definition you have the separate tasks:

    1. sort the list by keys
    2. group the result by keys
    3. turn it into a list of the desired type

    Once again, separation of concerns (modularity) is an important principle. Just try to apply it to small problems and once you gained some experience you will be able to come up with surprisingly simple solutions to seemingly difficult problems.

提交回复
热议问题