Home > Software engineering >  Count the number of 'a' and 'A' characters in a string using only recursion and
Count the number of 'a' and 'A' characters in a string using only recursion and

Time:10-16

Implement the countA :: [Char] -> Int function that counts the number of occurrences of the characters a and A in a string.

Hint: Whether an item is a or A or some other element can be checked by using pattern matching.


For example:

countA "Appleapplet" == 2

countA "Nietzsche" == 0

I'm a beginner at learning Haskell and the first thing that came to mind was to do an if-then-else statement but that can't be the answer, because I have to do this with pattern matching. I don't even know where to begin and I don't fully understand how pattern matching works on lists. I can't use any imported functions in this exercise.

CodePudding user response:

You can use an if-then-else to check if the first character of a list is 'a' or 'A', although pattern matching might be more elegant.

What you need is a recursive function with as base case the empty list (1), in that case the total number of times that a or A occurs is 0. For the recursive case, we work with a non empty list with x the first character, and xs the (possibly empty) tail of the list. We can in that case check if the first character x is equal to 'a' or 'A' and in that case increment the result of the recursive call. We thus can implement this as:

countA :: String -> Int
countA [] = …  -- (1)
contaA (x:xs) = if x == 'a' || x == 'A' thenelse-- (2)

where you still need to fill in the parts. The ones in the second case (2) will need to make recursive calls.

  • Related