gpt4 book ai didi

haskell - 为什么 `putStrLn getLine` 不起作用?

转载 作者:行者123 更新时间:2023-12-02 01:55:51 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com