由于类型不匹配导致的代码中的错误
问题描述:
在此代码中存在错误起因以致不匹配。由于类型不匹配导致的代码中的错误
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
的错误信息是:
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
如何删除错误
答
从您的意见,您的loop
函数应返回IO [Int]
,就像这样:
loop :: Int -> IO [Int]
那么第一种情况是:
loop 0 = return []
第二个应该与您所写的相似(不通过ls
这是您的结果,而不是输入)。
BTW,误差可以这样解释的:
loop :: Int -> [Int] -> IO() -- line 1
loop 0 ls = return ls -- line 2
在第1行,你告诉了loop
函数有两个参数,一个Int
和[Int]
编译器。在第2行中,您使用0
(这是一个Int,因此很好)和ls
。所以,ls
的类型是[Int]
。 return
的签名是return :: a -> m a
,返回类型取决于Monad m
(在您的情况下为IO
)和输入类型为[Int]
。因此,return ls
的类型是IO [Int]
,但是您在第1行告诉编译器它应该是`IO()'。 (究竟是什么编译器告诉你该错误消息。;-))
答
ls
具有类型[Int]
,所以return ls
具有类型IO [Int]
。但是,您的类型签名表示该函数应该返回IO()
。它看起来像你只是错误的类型签名。这应该工作:
loop :: Int -> [Int] -> IO [Int]
@tikhon请看这段代码 – 2012-01-16 08:55:55
你想用'循环'功能完成什么?它的签名表示它需要一个整数('Int')整数列表('[Int]')并返回一个操作。 – Andre 2012-01-16 09:10:48
我想让循环运行n次,并最终返回n个数字列表 – 2012-01-16 09:13:00