import Prelude hiding (print, putStr, putStrLn, getLine, all) -- duplicate an I/O action: dupAct :: IO () -> IO () dupAct act = act >> act test1 = dupAct (putStr "Hi") >> putChar '\n' -- multplicate an I/O action: multAct :: Int -> IO () -> IO () --multAct n act = foldr1 (>>) (take n (repeat act)) multAct n = foldr1 (>>) . take n . repeat test2 n = multAct n (putStr "Hi") >> putChar '\n' fac :: Integer -> Integer fac n = if n==0 then 1 else n * (fac (n - 1)) test3 n = putStr (show (fac n)) print :: Show a => a -> IO () print x = putStrLn (show x) test4 n = print (fac n) -- prints a string putStr :: String -> IO () putStr "" = return () putStr (c:cs) = putChar c >> putStr cs -- prints a string with a newline putStrLn :: String -> IO () putStrLn s = putStr s >> putChar '\n' -- reads a line from the terminal getLine :: IO String getLine = getChar >>= \c -> if c == '\n' then return "" else getLine >>= \cs -> return (c:cs) getLine' :: IO String getLine' = do c <- getChar if c == '\n' then return "" else do cs <- getLine' return (c:cs) -- prints all intermediate results facO :: Integer -> IO Integer facO n = if n==0 then return 1 else do f <- facO (n - 1) print (n - 1, f) return (n * f) facInteractive :: IO () facInteractive = do putStr "Which n? " str <- getLine facn <- facO (read str) putStrLn ("The result is " ++ show facn) -- prints the number of characters in a file fileLength :: String -> IO () fileLength f = readFile f >>= print . length -- prints the number of lines of a file fileLines :: String -> IO () fileLines f = readFile f >>= print . length . lines -- prints the number of empty lines of a file fileEmptyLines :: String -> IO () fileEmptyLines f = readFile f >>= print . length . filter (all (==' ')) . lines all :: (a -> Bool) -> [a] -> Bool all p xs = foldr (&&) True (map p xs) enumerateLines :: String -> String enumerateLines = unlines . map (uncurry (++)) . zip (map (\i -> show i ++ ": ") [1..]) . lines enumerateFileLines :: String -> IO () enumerateFileLines s = readFile s >>= putStr . enumerateLines