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

标签 haskell stdio

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

相关文章:

c - 如何使这段代码形成的金字塔(CS50马里奥程序)右对齐?

c - getch() 和 getchar() 有什么区别?

haskell - Haskell 中的异构引用相等性

haskell - Haskell 中类型类的类型级别指示符函数

haskell - 在 Haskell 函数定义的参数符号之间使用冒号有什么作用?

unix - C stdio 输入流如何实现行缓冲?

c - 如何使用 stdio.h 在 C 中的二维数组中记录多个最大值

haskell - 不安全 IO 或 : Haskeline and Directories

haskell - Haskell 中的类型级多态性

c - getc() 不返回回车符 '\r' 字符