我是 Haskell 的新手。
我的 Haskell 脚本与 GHCi
,
Prelude> let a = putStrLn getLine
犯了这样的错误。
<interactive>:1:17:
Couldn't match expected type `String'
against inferred type `IO String'
In the first argument of `putStrLn', namely `getLine'
In the expression: putStrLn getLine
In the definition of `a': a = putStrLn getLine
Prelude>
为什么它不起作用以及如何打印从 stdin
输入的内容?
最佳答案
putStrLn :: String -> IO ()
getLine :: IO String
类型不匹配。 getLine
是一个 IO
操作,putStrLn
接受一个纯字符串。
您需要做的是绑定(bind) IO
monad 内的行,以便将其传递给 putStrLn
。以下是等效的:
a = do line <- getLine
putStrLn line
a = getLine >>= \line -> putStrLn line
a = getLine >>= putStrLn
关于haskell - 为什么 `putStrLn getLine` 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5216473/