Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `putStrLn getLine` work?

Tags:

haskell

stdio

I'm complete 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?

like image 621
eonil Avatar asked Mar 07 '11 06:03

eonil


1 Answers

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
like image 160
ephemient Avatar answered Nov 06 '22 06:11

ephemient