File: part14.lhs

package info (click to toggle)
haskell98-tutorial 200006-2-1.1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 864 kB
  • ctags: 59
  • sloc: haskell: 2,125; makefile: 66; sh: 9
file content (71 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
Gentle Introduction to Haskell 98, Online Supplement 
Part 14
Covers Section 7, 7.1, 7.2

> module Part14 where

> import Prelude hiding (putStr, getLine, sequence_)
> import IO (isEOFError)

Both putStr and getLine are actually in the prelude.

Section: 7  I/O

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

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

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

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

> e3 = do putStr "Type Something: "
>         str <- getLine
>         putStrLn ("You typed: " ++ str)

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

Continued in part15.lhs