Home > Net >  Haskell - Returning a list of n lists that count frequencies of each character in string
Haskell - Returning a list of n lists that count frequencies of each character in string

Time:11-15

I'm new to Haskell and I'm currently trying to solve a little problem.

I want to create a function occurrences that is defined as such:

occurrences:: Int -> String -> [[(Char, Int)]]

The function accepts an Int and String as its parameters; where Int represents the number of occurrence lists to be printed. The number of occurrences for each character should be sorted in descending order.

For example, occurrences 2 'hi' should return [[('h', 1), ('i', 1)], [('h', 1), ('i', 1)]] and occurrences 3 'foo' would return [[('o', 2), ('f', 1)], [('o', 2), ('f', 1)], [('o', 2), ('f', 1)]]

So far I've added the below as part of my implementation for the occurrences function.

occurrences str = map (\x -> [(head x, length x)]) $ group $ sort str

But this just prints [[('h',1)],[('i',1)]] rather than [[('h', 1), ('i', 1)]] and I'm not sure how to return n number of lists according to the input as I'm new to Haskell.

Can I get help on this please?

CodePudding user response:

You can convert [[('h',1)],[('i',1)]] to [('h', 1), ('i', 1)] using concat. Once you've done that, you'd want to replicate it the specified number of times.

CodePudding user response:

It works well.

import Data.List
import Data.Ord (comparing) 

occurrences n = replicate n . reverse . sortBy (comparing snd) . map (\x -> (head x, length x)) . group . sort
main = print $ occurrences 3 "aabaccaccbbcc"

output:

[[('c',6),('a',4),('b',3)],[('c',6),('a',4),('b',3)],[('c',6),('a',4),('b',3)]]
  • Related