-- code_2009_03_04.hs
-- Glenn G. Chappell
-- 4 Mar 2009
--
-- For CS 331 Spring 2009
-- Sample Haskell code
-- From the Wednesday, March 4, 2009 class meeting

module Main where


-- ---------------------------------------------------------------------
-- Code from topic Haskell: I/O
-- ---------------------------------------------------------------------


-- Simple I/O

-- Hello world
io1 = putStrLn "Hello, world!"

-- Without newline
io2 = putStr "No newline after this"

-- Printing a non-string value
io3 = putStrLn s where
    s = show (5*4+3)         -- "show" converts anything to a String

-- "do" wraps a sequence of I/O actions into a single I/O action
io4 = do
    putStrLn "First line"
    putStrLn "Second line"
    putStr "My favorite number is: "
    print (7*7-7)            -- print x = putStrLn (show x)
    putStrLn "Fourth line"

io5 = do
    io4
    putStrLn "Fifth Line"

-- Read & write

io6 = do
    putStr "Type something: "
    line <- getLine          -- "getLine" gets a line & returns String
                             -- "<-" binds name to result, within "do"
    putStr "You typed (backwards): "
    putStrLn (reverse line)  -- Can call non-I/O func from I/O func
                             -- But not vice-versa

-- Writing getLine ourselves
myGetLine = myGetLine_recurse "" where
    myGetLine_recurse str = do
        c <- getChar          -- getChar gets a Char (duh)
        if (c == '\n')
            then return str
            else myGetLine_recurse (str ++ [c])

-- Read/write loop
-- Has no error checking!
io7 = do
    putStr "Type a number (0 to end): "
    line <- myGetLine
    let value = read line    -- "let" for non-I/O values
                             -- "read" converts a String to anything
    if (value == 0)          -- From here on is single expression
        then return ()       -- "return ()": a do-nothing I/O action
        else do
            putStr "Adding 10, we get: "
            putStrLn (show (value + 10))
            io7              -- Recurse for "loop"
                             -- Tail recursion, can easily be eliminated

