import IO (isEOFError)
Both putStr and getLine are actually in the prelude.
putStr 和 getLine 其实都在 Prelude 中。
Section: 7 I/O
第 7 节 I/O(输入/输出)
Section 7.1
第 7.1 节
The I/O monad divides the Haskell world into values and actions. So far, we have only used values but now we need to execute actions. Hugs looks at the type of an expression typed at the prompt. If the type is an IO type, the expression is assumed to be an action and the action is invoked. If the type is not IO t (for any t), then the expression value is printed.
I/O monad 把 Haskell 的世界分为值与动作。到目前为止我们只用过值,
而现在需要执行动作了。Hugs 会查看你在提示符下输入的表达式(的
类型)。如果类型是 IO 类型,该表达式就被当作一个动作并被执行。如果
类型不是 IO t(对任何 t 都不是),那么就打印该表达式的值。
e1 = do c <- getChar
putChar c
ready = do c <- getChar
return (c == 'y')
The print function converts a value to a string (using the Show class) and prints it with a newline at the end.
print 函数把一个值转换为字符串(利用 Show 类)并打印出来,末尾
附加一个换行。
e2 = do r <- ready
print r
You can't put the call to ready and print in the same expression. This would be wrong:
e2 = print (ready)
你不能把对 ready 的调用和 print 放在同一个表达式里。这样是错的:
e2 = print (ready)
getLine :: IO String
getLine = do c <- getChar
if c == '\n'
then return ""
else do l <- getLine
return (c:l)
putStrLn prints a string and adds a newline at the end.
putStrLn 打印一个字符串,并在末尾加上换行。
e3 = do putStr "Type Something: "
str <- getLine
putStrLn ("You typed: " ++ str)
Section 7.2
第 7.2 节
todoList :: [IO ()]
todoList = [putChar 'a',
do putChar 'b'
putChar 'c',
do c <- getChar
putChar c]
sequence_ :: [IO ()] -> IO ()
sequence_ = foldr (>>) (return ())
e4 = sequence_ todoList
putStr :: String -> IO ()
putStr s = sequence_ (map putChar s)
e5 = putStr "Hello World"