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

前端 未结 7 1292
谎友^
谎友^ 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:14

    Use list comprehension, no need for any imports or sorting.

    [ (x,c) | x<-['A'..'z'], let c = (length.filter (==x)) "happy", c>0 ]
    

    Result:

    [('a',1),('h',1),('p',2),('y',1)]
    

    Above is the filtered and rewritten (only character with count > 0) from:

    [(x,(length.filter (==x)) "happy" ) | x<-['A'..'z']]
    

    Explanation:

    • Make a list of all characters that match a given character (A..z).
    • For each character, count this list (==length)
    • Put this count in a tuple with the character

提交回复
热议问题