Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of Instances of Char in a given String Haskell

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?

like image 665
user2863323 Avatar asked Oct 10 '13 13:10

user2863323


People also ask

How do you count occurrences of a given character in a String?

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.

Is a String a list of chars in Haskell?

Because in haskell, a String is a list of characters, i.e. [Char] , just returning the input as given will do.

Are there strings in Haskell?

A String is a list of characters. String constants in Haskell are values of type String .


2 Answers

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.

like image 175
bheklilr Avatar answered Oct 29 '22 20:10

bheklilr


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)).

like image 41
Bartek Banachewicz Avatar answered Oct 29 '22 20:10

Bartek Banachewicz