-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.hs
More file actions
69 lines (55 loc) · 1.69 KB
/
interactive.hs
File metadata and controls
69 lines (55 loc) · 1.69 KB
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
module InteractiveIO where
import Prelude hiding (getLine, putStr, putStrLn)
--interactive programs have side effects
--e.g. readline is not a mathematical function- you call it with no arguments,
--but it always returns different results (it has side effects)
--
--the IO monad expresses in the type of a function, that it has side effects
--IO a
--action returning type a, that has side effects
--IO Char
--IO () --returns nothing, but has side effects - like returning void
--what do we already have in the IO Monad:
--getChar :: IO Char
--putChar :: Char -> IO ()
--return :: a -> IO a
a :: IO (Char, Char)
a = do x <- getChar
getChar
y <- getChar
return (x, y)
getLine :: IO String
getLine = do x <- getChar
if x == '\n' then
return []
else
do xs <- getLine
return (x:xs)
putStr :: String -> IO ()
putStr [] = return ()
putStr (x:xs) = do putChar x
putStr xs
putStrLn :: String -> IO ()
putStrLn xs = do putStr xs
putChar '\n'
strlen :: IO ()
strlen = do putStrLn "Enter a string:"
xs <- getLine
putStr "The string has "
putStr (show (length xs))
putStrLn " characters"
putStr' :: String -> IO ()
putStr' [] = return ()
putStr' (x:xs) = putChar x >> putStr' xs
putStrLn' :: String -> IO ()
putStrLn' [] = putChar '\n'
putStrLn' xs = putStr' xs >>= \x -> putChar '\n'
getLine' = get []
get :: String -> IO String
get xs = do x <- getChar
case x of
'\n' -> return xs
_ -> get (xs ++ [x])
interact' :: (String -> String) -> IO ()
interact' f = do xs <- getLine'
putStrLn' (f xs)