'How can I safely access each element in a Haskell list?
I am new to Haskell and the syntax has been giving me a bit of trouble, especially in understanding how to iterate. I am creating a method what will process a string and return a list of tuples containing each letter and their number of occurences.
The tuples do reappear with duplicate letters so a list like "abba" should return [('a',2), ('b',2), ('b',2), ('a',2)]
counting_letters :: Eq a => [a] -> [(a,Int)]
counting_letters [] = []
counting_letters list
| length list == 0 = []
| otherwise = [(x,c) | x <- [head list], let c = (length.filter(==x)) list]
Right now, the only cases that work as expected are the empty list and single element lists such as "a". I understand that this only points to the head but when I attempted to use [head list .. last list]
it gave me an error that it could not deduce (Enum a). How can I safely access each element in a list?
Solution 1:[1]
The behavior you desire is simply
counting_letters :: Eq a => [a] -> [(a,Int)]
counting_letters list = [(x,c) | x <- list, let c = (length.filter(==x)) list]
without any special cases.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Louis Wasserman |