How to find the frequency of characters in a string in Haskell?

前端 未结 7 1290
谎友^
谎友^ 2020-12-11 15:08

How can I count the frequency of characters in a string and then output them in sort of a table?

For example, if I input the word \"happy\" the result would be

7条回答
  •  我在风中等你
    2020-12-11 15:23

    The simplest solution is to use a Data.Map to store the intermediate mapping from character to frequency. You can then construct the counts easily using fromListWith. Since Data.Map is sorted, you get them in ASCII order for free.

    λ> :m + Data.Map
    λ> let input = "happy"
    λ> toList $ fromListWith (+) [(c, 1) | c <- input]
    [('a',1),('h',1),('p',2),('y',1)]
    

    So what's happening here?

    The idea is to build a Data.Map (a tree map) using the characters as keys and the frequencies as values.

    First, we take the input string and make tuples of each character with a 1 to indicate one occurrence.

    λ> [(c, 1) | c <- input]
    [('h',1),('a',1),('p',1),('p',1),('y',1)]
    

    Next, we use fromListWith to build a sorted map from these key-value pairs by repeatedly inserting each key-value pair into a map. We also give it a function which will be used when a key was already in the map. In our case, we use (+) so that when a character is seen multiple times, we add the count to the existing sum.

    Finally we covert the map back into a list of key-value tuples using toList.

提交回复
热议问题