-- | Input/Output in Haskell -- Examples to introduce and illustrate how I/O works in Haskell -- Functional Programming course 2016. -- Thomas Hallgren {- This is just a skeleton, the definitions will be filled in during the lecture. -} import Data.List(sort) main = showTheDifference2 showTheDifference1 :: IO () showTheDifference1 = do putStrLn "Enter two numbers" x <- readLn y <- readLn putStr "The difference is: " print (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 diff <- getTheDifference putStr "The difference is: " print diff copyFile :: FilePath -> FilePath -> IO () copyFile from to = do s <- readFile from writeFile to s sortFile :: FilePath -> FilePath -> IO () sortFile from to = do s <- readFile from writeFile to (sortLines s) 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 = do print 42 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 numbers 0 = return () numbers n = do print n numbers (n-1)