Simple problem.
Given a String, I want to be able to enter a letter and then have my function count the number of times that letter appears in a string.
countLetters :: String -> Char -> Int
How can this be done?
First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Because in haskell, a String is a list of characters, i.e. [Char] , just returning the input as given will do.
A String is a list of characters. String constants in Haskell are values of type String .
With
countLetters :: String -> Char -> Int
countLetters str c = length $ filter (== c) str
This gets only the characters in str
that equal c
, then computes the length of that.
That depends on the number of calls you'd like to make to one String
. Simple solution would be to just read every character in the string, if it matches the one you're looking for, increase the counter.
Now, if you're mapping over something with a counter, you can obviously use fold
:
countLetters xs x = foldl (\count char -> if char == x then (count + 1) else count) 0 xs
However, if you want to do many queries, it makes more sense to build the lookup table (i.e. sort) first. Then you can get the number of repetitions of arbitrary character in O(1)
(the whole algorithm is still O(n)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With