Haskell Language Reading from `stdin`


Example

As-per the Haskell 2010 Language Specification, the following are standard IO functions available in Prelude, so no imports are required to use them.

getChar :: IO Char - read a Char from stdin

-- MyChar.hs
main = do
  myChar <- getChar
  print myChar

-- In your shell

runhaskell MyChar.hs
a -- you enter a and press enter
'a'  -- the program prints 'a'

getLine :: IO String - read a String from stdin, sans new line character

Prelude> getLine
Hello there!  -- user enters some text and presses enter
"Hello there!"

read :: Read a => String -> a - convert a String to a value

Prelude> read "1" :: Int
1
Prelude> read "1" :: Float
1.0
Prelude> read "True" :: Bool
True

Other, less common functions are:

  • getContents :: IO String - returns all user input as a single string, which is read lazily as it is needed
  • interact :: (String -> String) -> IO () - takes a function of type String->String as its argument. The entire input from the standard input device is passed to this function as its argument