-- Starting file for HW 11 import Prelude hiding(repeat) import List import IO ------------------------------------------------------------------------ -- For problems 1 and 2. ones, nums :: [Integer] ones = 1:ones nums = 0:zipWith (+) ones nums ------------------------------------------------------------------------ -- For problems 3 and 4 -- getInt reads an Int from an input line and returns it (from Thompson) getInt :: IO Int getInt = do line <- getLine return (read line :: Int) -- From Thompson page 392 while :: IO Bool -> IO () -> IO () while test action = do res <- test if res then do action while test action else return () -- sizen n xs (Something that might be handy for 18.9) -- tests if the length of lst is less than n. sizen :: Int -> [Int] -> IO Bool sizen n lst = do return (length lst < n) -- getNextInt xs (Something that might be handy for 18.9) -- gets an Int, x, from input, and returns (x:xs) getNextInt :: [Int] -> IO [Int] getNextInt xs = do x <- getInt return (x:xs) -- notEOL, tests if we are *not* at the end of the input line. -- If we are at the end of the line, we read past it. notEOL :: IO Bool notEOL = do c <- hLookAhead stdin if c /='\n' then return True else do getChar return False isEOL :: IO Bool isEOL = do { res <- notEOL; return (not res) } -- showMe action -- prints what the action returns. E.g., try: -- showMe getInt showMe :: Show a => IO a -> IO () showMe action = do x <- action putStr "Here is what is returned: " print x -- notEOF, tests if we are *not* at the end of the input file. notEOF :: IO Bool notEOF = do res <- isEOF return (not res) -- stutter, reads a character and echos it twice stutter = do c <- getChar; putChar c; putChar c; -- readAndEcho, reads characters and stutters them back until the -- EOF is reached (i.e., until you hit a a control-D). readAndEcho = while notEOF stutter -- Consider: -- readAndEcho' = repeat isEOF stutter -- once you have defined repeat. ------------------------------------------------------------------------ -- For problem 4, here is a start on whileG whileG :: (a -> IO Bool) -> (a -> IO a) -> a -> IO a whileG test action x = do res <- test x error "the rest of the definition is missing" getNints :: Int -> IO [Int] getNints n = whileG (sizen n) getNextInt [] getThree = do xs <- getNextInt [] xs' <- getNextInt xs xs'' <- getNextInt xs' return xs''