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

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

    I'll scetch a solution step by step. A shorter solution is possible using standard functions.

    You want a sorted result, therefore

    result = sort cs
        where
    

    cs would be a list of tuples, where the first element is the character and the second element is the number of times it appears.

            cs = counts "happy"
            counts [] = []
            counts (c:cs) = (c, length otherc + 1) : counts nonc where
                 (otherc, nonc) = partition (c==) cs
    

    That's all.

    Interestingly, counts works on any list of items that support the == operator.

    0 讨论(0)
提交回复
热议问题