home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gofer230.zip / Progs / Gofer / Demos / iosynch.gs < prev    next >
Text File  |  1994-06-23  |  2KB  |  47 lines

  1. -- This file contains the example program from section 7.7 of the Haskell
  2. -- report (version 1.1) for a program using synchronisation.
  3.  
  4. main :: Dialogue
  5. main  = readChan stdin abort (\userInput -> readNums (lines userInput))
  6.  
  7. readNums           :: [String] -> Dialogue
  8. readNums inputLines = readInt "Enter first number: " inputLines
  9.                         (\num1 inputLines1 ->
  10.                           readInt "Enter second number: " inputLines1
  11.                             (\num2 _ -> reportResult num1 num2))
  12.  
  13. reportResult       :: Int -> Int -> Dialogue
  14. reportResult num1 num2
  15.   = appendChan stdout ("Their sum is: "++ show (num1 + num2)) abort done
  16.                                   
  17.  
  18. -- readInt prints a prompt and then reads a line of input.  If the
  19. -- line contains an integer, the value of the integer is passed to the
  20. -- success continuation.  If a line cannot be parsed as an integer,
  21. -- an error message is printed and the user is asked to try again.
  22. -- If EOF is detected, the program is aborted.
  23.  
  24. readInt :: String -> [String] -> (Int -> [String] -> Dialogue) -> Dialogue
  25. readInt prompt inputLines succ
  26.   = appendChan stdout prompt abort
  27.       (case inputLines of
  28.          (l1 : rest) -> case (intRead l1) of
  29.                           [(n,"")] -> succ n rest
  30.                           _        -> appendChan stdout
  31.                                        "Error - retype the number\n" abort
  32.                                        (readInt prompt rest succ)
  33.          _           -> appendChan stdout "Early EOF" abort done)
  34.  
  35. -- Since the Gofer standard prelude does not include the reads function in
  36. -- the Text class, we have explicitly specified intRead in the definition
  37. -- above (rather than "reads" as used in the Haskell report).
  38. -- A straightforward (if rather crude) definition of this function follows:
  39.  
  40. intRead   :: String -> [(Int,String)]
  41. intRead "" = []
  42. intRead s  = loop 0 s
  43.              where loop n []        = [(n,"")]
  44.                    loop n s@(d:ds)
  45.                        | isDigit d  = loop (10*n+(ord d - ord '0')) ds
  46.                        | otherwise  = [(n,s)]
  47.