Search code examples
haskellfunctional-programmingchartuples

Count occurrences in a string


I am very new to Haskell and am stuck on a problem. The problem is that i need to make a function that takes in a string and returns a list of tuples. The tuple will consist of (character, the number of times that character has appeared in a string).

So far i have written this.

charCountTup :: [Char] -> [(Char,Integer)]
charCountTup xs = map (\ x -> (x, 1)) xs

input of the string "Hello" will give me

('H',1),('e',1),('l',1),('l',1),('o',1)].

what i want is

('H',1),('e',1),('l',2),('o',1)]

i don't want to worry about uppercase and lowercase for now. Anyone more familiar with haskell that has any ideas on how i can increment my tuples' integer based on if it has appeared more than once?


Solution

  • A bit clumsy .. it's technically a partial function with 'head' in it, but I don't think 'group' returns and empty string. I was lazy and changed your 'Integer' to 'Int'

    import Data.List (group, sort)
    
    xs = "hello world"
    
    count :: String -> [(Char,Int)]
    count  xs = 
        map (\grp -> (head grp, length grp)) (group $ sort xs)
        
    count xs
    
    

    [(' ',1),('d',1),('e',1),('h',1),('l',3),('o',2),('r',1),('w',1)]

    I just realized that you can write it using list comprehensions ..

    [(head grp, length grp) | grp <- (group $ sort xs)]