module Exercises.ChapterTen
  ( adder
  , readline
  , seqAdder
  ) where

import Control.Monad

adder :: IO ()
adder = do
  putStr "How many numbers? "
  num <- getLine
  adder' 0 $ read num

adder' :: Int -> Int -> IO ()
adder' t r = do
  x <- getLine
  let total = t + read x :: Int
  if r == 1
    then putStrLn $ "The total is " ++ show total
    else adder' total (r - 1)

seqAdder :: IO ()
seqAdder = do
  putStr "How many numbers? "
  num <- getLine
  strings <- replicateM (read num :: Int) getLine
  putStr "The total is "
  print (sum $ map (read :: String -> Int) strings)

readline :: IO String
readline = do
  x <- getChar
  if x == '\DEL'
    then do
      putChar '\b'
      putChar ' '
      putChar '\b'
      readline
    else do
      putChar x
      xs <- readline
      return (x : xs)
