开发者

Why doesn't `putStrLn getLine` work?

开发者 https://www.devze.com 2023-02-15 09:33 出处:网络
I\'m c开发者_如何学Goomplete newbie on Haskell. My Haskell script with GHCi, Prelude> let a = putStrLn getLine

I'm c开发者_如何学Goomplete newbie on Haskell. My Haskell script with GHCi,

Prelude> let a = putStrLn getLine

makes an error like this.

<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> 

Why doesn't it work and how can I print something input from stdin?


putStrLn :: String -> IO ()
getLine :: IO String

The types do not match. getLine is an IO action, and putStrLn takes a plain string.

What you need to do is bind the line inside the IO monad in order to pass it to putStrLn. The following are equivalent:

a = do line <- getLine
       putStrLn line

a = getLine >>= \line -> putStrLn line

a = getLine >>= putStrLn
0

精彩评论

暂无评论...
验证码 换一张
取 消