Reputation: 3247
In this code there is an error sue to mismatch.
import System.IO
loop :: Int -> [Int] -> IO ()
loop 0 ls = return ls
loop n ls = do newNumber <- readLn
loop (n-1) (newNumber:ls)
main = do
putStrLn "Please enter the number"
number <- readLn :: IO Int
putStrLn $ "The num is:" ++ show number
xs <- loop number []
print xs
The error message is:
treep.hs:4:20:
Couldn't match expected type `()' with actual type `[Int]'
In the first argument of `return', namely `ls'
In the expression: return ls
In an equation for `loop': loop 0 ls = return ls
how can i remove the error
Upvotes: 0
Views: 391
Reputation: 1607
From your comment, your loop
function should return IO [Int]
, like so:
loop :: Int -> IO [Int]
Then the first case is:
loop 0 = return []
The second one should be similar to what you wrote (without passing in ls
which is your result, not an input).
BTW, the error can be explained this way:
loop :: Int -> [Int] -> IO () -- line 1
loop 0 ls = return ls -- line 2
In line 1, you tell the compiler that the loop
function takes two arguments, an Int
and a [Int]
. In line 2, you use 0
(which is an Int, thus it's fine), and ls
. So, ls
is of type [Int]
. The signature for return
is return :: a -> m a
, the return type depends on the Monad m
(in your case IO
) and on the input type which is [Int]
. Therefore, the type of return ls
is IO [Int]
, but you told the compiler on line 1 that you it should be `IO ()'. (Exactly what the compiler told you by the error message. ;-) )
Upvotes: 2
Reputation: 139930
ls
has type [Int]
, so return ls
has type IO [Int]
. However, your type signature says that the function should return IO ()
. It looks like you simply got the type signature wrong. This should work:
loop :: Int -> [Int] -> IO [Int]
Upvotes: 2