90 likes | 266 Views
CS 152, Programming Paradigms Fall 2012, SJSU. Jeff Smith. Input and output. I/O functions are called actions. Actions have a return type labeled with “IO”. print :: Show a => a -> IO () putChar :: Char -> IO () getChar :: IO Char putStr :: String -> IO ()
E N D
CS 152, Programming ParadigmsFall 2012, SJSU Jeff Smith
Input and output • I/O functions are called actions. • Actions have a return type labeled with “IO”. • print :: Show a => a -> IO () • putChar :: Char -> IO () • getChar :: IO Char • putStr :: String -> IO () • putStrLn :: String -> IO ()
IO types and encapsulation • IO types are similar to Java wrapper classes • They encapsulate a value of a specified type • e.g., IO Char wraps a character • e.g., IO () wraps nothing • We’ll see later how values are unwrapped • and wrapped
Using actions • Actions can be evaluated by the interpreter • e.g. print ("abc" ++ "cde“) • Actions can be the body of a mainfunction • e.g., main = putStrLn "howdy!!"
I/O and main functions • Main bodies can have multiple actions. • They need to be introduced by do e.g. main = do print "enter a letter: " c <- getChar putStrLn "" print (replicate 5 c) • Here the <- operator unwraps the character
Exceptions, I/O, functional programming • Note that I/O is not congenial to the functional paradigm • e.g., getChar does not return the same value every time it is called • Haskell has a full-fledged exception mechanism available (and appropriate) for I/O.
The main function • Should have the only exceptional behavior of a module • Is what is run from the command line (perhaps with parameters) • Can be run from the Actions menu, by pressing F5, or by entering :m
Functions for printing • print is equivalent to putStrLn . show • putStrandputStrLndo not coerce their arguments to be strings • unlike toString in Java
Wrapping by I/O types • To wrap a value for an I/O type, use return • Do not confuse this with return in Java • It does not stop execution in any sense. • Examples of its use can be seen in the definition of the Prelude module.