Ticket #2148: Bug.3.hs

File Bug.3.hs, 1.0 KB (added by twhitehead, 6 years ago)

Further simplification (now just generates integer lists as a series of (:) thunks)

Line 
1module Main where
2
3import System
4import qualified System.IO as IO
5
6--------------------------------------------------------------------------------
7-- main loop
8--
9-- Endlessly generate the integer list [1..M], where M is read from the command
10-- line, from back to front as a sequence of thunks.
11---
12main = do IO.hSetBuffering IO.stdout IO.LineBuffering
13          args <- getArgs :: IO [String]
14          if length args /= 1 then do prog <- getProgName
15                                      fail $ "command line: " ++ prog ++ " depth"
16                                      else return ()
17          depth <- let arg=args!!0 in catch (read arg) $ \_ -> fail $ "depth should be an integer not " ++ show arg :: IO Int
18          forever 0 depth
19    where read :: (Read a) => String -> IO a
20          read xs = case [ x | (x,xs') <- reads xs, ("","") <- lex xs' ] of
21                    [x] -> return x
22                    _   -> fail "read: ambiguous parse"
23          forever :: Int -> Int -> IO ()
24          forever i d = do putStrLn $ "Starting block " ++ show i
25                           build d [] `seq` forever (i+1) d
26          build :: Int -> [Int] -> [Int]
27          build 0 xs = xs
28          build d xs = build (d-1) $ d : xs