Reputation: 87
I need to count how many digits appear in a list of characters using haskell.
eg. ['2','3','d','r','t','5']
would output 3
I have managed to do it using string but cannot get it to work while using characters
this is my code for string
isNumber' :: String -> Bool
isNumber' s = case (reads s) :: [(Int, String)] of
[(_,"")] -> True
_ -> False
counta :: [String] -> Int
counta = length . filter isNumber'
e.g. ['2','3','d','r','t','5']
would output 3
Upvotes: 1
Views: 310
Reputation: 113
You can use
Char -> Bool
instead of String -> Bool
and it should work without the read
Upvotes: 0
Reputation: 477607
Since you say it is a list of characters, the type of counta
should be:
counta :: [Char] -> Int
counta = length . filter isNumber'
So that means that isNumber'
has as signature Char -> Bool
, and thus checks if a character is a digit. We however do not need to implement such function: in the Data.Char
module, there is an isDigit :: Char -> Bool
function, so we can implement the counta
with:
import Data.Char(isDigit)
counta :: [Char] -> Int
counta = length . filter isDigit
Upvotes: 2
Reputation: 17806
Not far off, but your isNumber'
needs to take a character, not a string. So it would be of type
isNumber' :: Char -> Bool
Using read
is not necessary.
Upvotes: 1