mgt
mgt

Reputation: 87

Writing a function in haskell using recursion to determine how many digits there are in a list of characters

I need to count how many digits there are in a list of characters using recursion so for this list ['a','b','c','1','2','3'] the answer should be 3

I have managed to do it using this code but I am struggling to do it using recursion

counta :: [Char] -> Int 
counta = length . filter isDigit

Example:

Main> counta ['a','b','c','1','2','3']

Answer should be: 3

Upvotes: 2

Views: 284

Answers (2)

crjake
crjake

Reputation: 21

Here's a simple way - try to understand it before just using it.

counta :: [Char] -> Int
counta [] = 0
counta (c:cs)
 | isDigit c = 1 + counta cs
 | otherwise = counta cs

Upvotes: 2

chepner
chepner

Reputation: 530960

Like any recursive function over a list, start by handling the head and recursing on the tail.

counta :: [Char] -> Int
counta [] = _
counta (x:xs) = let this = _  -- something involving x
                    that = counta xs
                in _ -- something involving this and that

If you try to compile this, the compiler will tell exactly what type each _ should be, which should help you replace them with the correct expressions.

Upvotes: 3

Related Questions