我有一个简单的功能,如:
nth :: Integer -> Integer
Run Code Online (Sandbox Code Playgroud)
我尝试打印它的结果如下:
main = do
n <- getLine
result <- nth (read n :: Integer)
print result
Run Code Online (Sandbox Code Playgroud)
生成以下错误:
Couldn't match expected type `IO t0' with actual type `Integer'
In the return type of a call of `nth'
In a stmt of a 'do' expression:
result <- nth (read n :: Integer)
Run Code Online (Sandbox Code Playgroud)
也试过putStrLn和很多其他组合没有运气.
我无法理解,我需要一些帮助,因为我不完全理解这些东西是如何运作IO的.
Tho*_*son 14
nth是一个功能,而不是一个IO动作:
main = do
n <- getLine
let result = nth (read n :: Integer)
print result
Run Code Online (Sandbox Code Playgroud)
该do语法在monad中解开某些东西。箭头右手边的所有内容都必须位于IO monad内,否则类型不会检查。一个IO Integer是在你的程序的罚款。do是用于更明确功能的语法糖,其编写方式如下:
回顾 (>>=) :: m a -> (a -> m b) -> m b
main = getLine >>= (\x ->
nth >>= (\y ->
print y))
Run Code Online (Sandbox Code Playgroud)
但是nth不是一元值,因此应用该函数没有意义(>>=),因为该函数需要type IO a。
| 归档时间: |
|
| 查看次数: |
19123 次 |
| 最近记录: |