I am a beginner and I was trying to write a function that check if a string can be interpreted to number or not. Here is my code:
string' xs = if (all isDigit xs == False)
then "can not be interpreted"
else read xs::Int
But it keeps reporting the error " Couldn't match expected type ‘[Char]’ with actual type ‘Int’ " I don't know why, has someone ever met this problem?
string'
- is itstring' :: String -> String
orstring' :: String -> Int
? In haskell, you can't have a function that returns one of two different types based on runtime properties of the input. – Daniel Martinreads :: String -> [(Int, String)]
, which will check that the input is well-formed for you, returning[]
if not (and a list with the successful parse and whatever was left unparsed if so). – Daniel Wagnernot (...)
instead of(...) == False
. This is a matter of taste, but the first looks more "natural". Alternatively, remove that completely and swap the then/else branches. (Daniel's suggestion above aboutreads
would be even better.) – chi