-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIO.hs
68 lines (52 loc) · 1.92 KB
/
IO.hs
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
-- | Input/Output in Haskell
-- Examples to introduce and illustrate how I/O works in Haskell
-- Functional Programming course 2018.
-- Thomas Hallgren
{-
This started as a skeleton, the definitions were filled in
during the lecture.
-}
import Data.List(sort)
main = showTheDifference2
-- | Read two numbers x & y and show the difference x-y
showTheDifference1 :: IO ()
showTheDifference1 = do putStrLn "Enter two numbers:"
x <- readLn
y <- readLn
putStrLn ("The difference is: "++show (x-y))
-- | Using 'return' to return results from IO actions
getTheDifference :: IO Integer
getTheDifference = do putStrLn "Enter two numbers:"
x <- readLn
y <- readLn
return (x-y)
-- | Reimplementation of showTheDifference1, using getTheDifference
showTheDifference2 :: IO ()
showTheDifference2 = do d <- getTheDifference
putStrLn ("The difference is: "++show d)
-- | Copy a file
copyFile :: FilePath -> FilePath -> IO ()
copyFile from to = do text <- readFile from
writeFile to text
-- | Sort the lines in a text file
sortFile :: FilePath -> FilePath -> IO ()
sortFile from to = do text <- readFile from
let sorted = sortLines text
writeFile to sorted
sortLines = unlines . sort . lines
doTwice :: IO a -> IO (a,a)
doTwice io = do x <- io
y <- io
return (x,y)
don't :: IO a -> IO ()
don't io = return ()
-- | Reimplementation of getTheDifference, using doTwice
getTheDifference2 :: IO Integer
getTheDifference2 = do putStrLn "Enter two numbers:"
(x,y) <- doTwice readLn
return (x-y)
-- | An example of combining do blocks and recursion to print some numbers
numbers :: Int -> IO ()
numbers 0 = return ()
numbers n = do print n
numbers (n-1)