Cse536 Functional Programming 1 6/30/2015 Lecture #16, Nov. 29, 2004 Todays Topics – Files, Channels, and Handles –IO exception handling –First Class Channels.

Slides:



Advertisements
Similar presentations
Kathleen Fisher cs242 Reading: Tackling the Awkward Squad, Sections 1-2Tackling the Awkward Squad Real World Haskell, Chapter 7: I/OReal World Haskell.
Advertisements

Cse536 Functional Programming 1 1/13/2015 Lecture #13, Nov. 08, 2004 Today’s Topics –Simple animations –Buffered graphics –Animations in Haskell –Complex.
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
Lab 9 CIS 370 Umass Dartmouth.  A pipe is typically used as a one-way communications channel which couples one related process to another.  UNIX deals.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
Chapter 16 Communicating With the Outside World. Motivation  In Chapter 3 we learned how to do basic IO, but it was fairly limited.  In this chapter.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.
Chapter 3 Simple Graphics. Side Effects and Haskell  All the programs we have seen so far have no “side-effects.” That is, programs are executed only.
Chapter 17 Rendering Reactive Animations. Motivation  In the previous chapter we learned just enough about advanced IO and concurrency to develop a “renderer”
Advanced Programming Handout 12 Higher-Order Types (SOE Chapter 18)
Cse536 Functional Programming 1 6/23/2015 Lecture #17, Dec. 1, 2004 Todays Topics – Higher Order types »Type constructors that take types as arguments.
Cse536 Functional Programming 1 6/24/2015 Lecture #4, Oct 6, 2004 Reading Assignments –Begin Reading chapter 3 (Simple Graphics) of the Text Homework Assignment.
Chapter 13 A Module of Simple Animations. Motivation  In the abstract, an animation is a continuous, time-varying image.  But in practice, it is a sequence.
Cse502 Functional Programming 1 6/26/2015 Lecture #11, Nov. 4, 2002 Todays Topics –Using Calculation to prove 2 functions are equal »An example from class.
Advanced Programming Handout 10 A Module of Simple Animations (SOE Chapter 13)
Chapter 15 A Module of Reactive Animations. Motivation  The design of animations in Chapter 13 is elegant, and in fact has the feel of a small domain-specific.
CS510AP Quick Check Monads. QuickCheck Quick check is a Haskell library for doing random testing. You can read more about quickcheck at –
Cse536 Functional Programming 1 7/16/2015 Lecture #15, Nov. 15, 2004 Todays Topics – Simple Animations - Review –Reactive animations –Vocabulary – Examples.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
CSE 341 Programming Languages Racket Datatype Style Programming Zach Tatlock Spring 2014.
Case Study - Fractions Timothy Budd Oregon State University.
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. L13-1 October 26, 2006http:// Monadic Programming October.
1 Haskell Kevin Atkinson John Simmons. 2 Contents Introduction Type System Variables Functions Module System I/O Conclusions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
Chapter 15 Strings as Character Arrays
Grab Bag of Interesting Stuff. Higher Order types Type constructors are higher order since they take types as input and return types as output. Some type.
Haskell Chapter 9. More Input and More Output  Files and Streams  Transforming Input  Not covered  brackets  command-line arguments  bytestrings.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
24-Jun-16 Haskell Dealing with impurity. Purity Haskell is a “pure” functional programming language Functions have no side effects Input/output is a side.
Hank Childs, University of Oregon April 15 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Advanced Functional Programming 2010
Haskell Chapter 7.
Introduction to C++ (Extensions to C)
PROGRAMMING IN HASKELL
Haskell Chapter 9.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2013.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2017.
PROGRAMMING IN HASKELL
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Autumn 2018.
Haskell Dealing with impurity 30-Nov-18.
Haskell Dealing with impurity 30-Nov-18.
Review for Final Exam.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Autumn 2017.
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Input and Output.
Reactive Animations Todays Topics
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2016.
Haskell Dealing with impurity 8-Apr-19.
Grab Bag of Interesting Stuff
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Programming Languages
Haskell Dealing with impurity 29-May-19.
Simple Animations Today’s Topics Reading Assignment Simple animations
Haskell Dealing with impurity 28-Jun-19.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2019.
Advanced Functional Programming
Jeff West - Quiz Section 3
Presentation transcript:

Cse536 Functional Programming 1 6/30/2015 Lecture #16, Nov. 29, 2004 Todays Topics – Files, Channels, and Handles –IO exception handling –First Class Channels –Concurrency and ForkIO Reading – Read Chapter 16 – Communicating with the Outside World – Read Chapter 17 – Rendering Reactive Animations Assignment – Last homework assigned Wednesday. See webpage. Due Wednesday Dec. 8, Final Exam –scheduled for Wednesday Dec. 8, 2004

Cse536 Functional Programming 2 6/30/2015 Files and Handles The functions: writeFile :: FilePath -> String -> IO () appendFile :: FilePath -> String -> IO () are used to read and write to files, but they incur quite a bit of overhead if they are used many times in a row. Instead we wish to open a file once, then make many actions on the file before we close it for a final time. openFile :: FilePath -> IOMode -> IO Handle hClose :: Handle -> IO () data IOMode = ReadMode | WriteMode | AppendMode deriving (Eq, Ord, Ix, Bounded, Enum, Read, Show)

Cse536 Functional Programming 3 6/30/2015 File Modes A file mode tells how an open file will be used. Different modes support different operations. When in WriteMode hPutChar :: Handle -> Char -> IO () hPutStr :: Handle -> String -> IO () hPutStrLn :: Handle -> String -> IO () hPrint :: Show a => Handle -> a -> IO () When in ReadMode hGetChar :: Handle -> IO Char hGetLine :: Handle -> IO String

Cse536 Functional Programming 4 6/30/2015 Standard Channels and Errors Predefined standard Channels stdin, stdout, stderr :: Handle Error Handling while doing IO isEOFError :: IOError -> Bool -- Test if the EOF error ioError :: IOError -> IO a -- Raise an IOError catch :: IO a -> (IOError -> IO a) -> IO a -- Handle an Error Other IO types of errors and their predicates. –isAlreadyExistsError, isDoesNotExistError, –isAlreadyInUseError, isFullError, –isEOFError, isIllegalOperation, –isPermissionError, isUserError,

Cse536 Functional Programming 5 6/30/2015 IOError IOError is an abstract datatype – NOT and algebraic datatype, defined with data like [ ] or Tree Thus it does not admit pattern matching. Hence the use of all the IOError recognizing predicates. –isAlreadyExistsError, isDoesNotExistError, –isAlreadyInUseError, isFullError, –isEOFError, isIllegalOperation, –isPermissionError, isUserError This was a concious decision, made to allow easy extension of the kinds of IOErrors, as the system grew.

Cse536 Functional Programming 6 6/30/2015 Handling IO Errors Any action of type IO a may potentially cause an IO Error. The function –catch :: IO a -> (IOError -> IO a) -> IO a can be used to gracefully handle such an error by providing a “fix” getChar' :: IO Char getChar' = catch getChar (\ e -> return '\n') getChar2 :: IO Char getChar2 = catch getChar (\ e -> if isEOFError e then return '\n' else ioError e) –- pass non EOF errors on

Cse536 Functional Programming 7 6/30/2015 An Example getLine' :: IO String getLine' = catch getLine'' (\ e -> return ("Error: " ++ show e)) where getLine'' = do { c <- getChar2 ; if c == '\n' then return "" else do { l <- getLine' ; return (c:l) }

Cse536 Functional Programming 8 6/30/2015 Catching errors when opening files getAndOpenFile :: String -> IOMode -> IO Handle getAndOpenFile prompt mode = do { putStr prompt ; name <- getLine ; catch (openFile name mode) (\e -> do { putStrLn ("Cannot open: "++name) ; print e ; getAndOpenFile prompt mode }) }

Cse536 Functional Programming 9 6/30/2015 Copying Files main = do { fromHandle <- getAndOpenFile "Copy from: " ReadMode ; toHandle <- getAndOpenFile "Copy to: " WriteMode ; contents <- hGetContents fromHandle ; hPutStr toHandle contents ; hClose fromHandle ; hClose toHandle ; putStr "Done\n" }

Cse536 Functional Programming 10 6/30/2015 First Class Channels A Channel is a special kind of abstraction, in the multiprocessing (or concurrency) paradigm. If you “pull” on the tail of a channel, and it is null, then you “wait” until something becomes available. First Class Channel Operations newChan :: IO (Chan a) writeChan :: Chan a -> a -> IO () readChan :: Chan a -> IO a getChanContents :: Chan a -> IO [a] isEmptyChan :: Chan a -> IO Bool

Cse536 Functional Programming 11 6/30/2015 Example ex1 = do { c <- newChan ; writeChan c 'a' ; writeChan c 'b' ; a <- readChan c ; b <- readChan c ; print [a,b] ; return [a,b] } It is easy to cause deadlock Using Channels just flipping the order of the writeChan and the readChan actions will do it

Cse536 Functional Programming 12 6/30/2015 Channels are used to communicate Independent (concurrent) processes can communicate through channels. An independent, concurrent process is started in Haskell with the forkIO primitive. forkIO :: IO () -> IO () ex2 :: IO() ex2 = do { c1 <- newChan :: IO(Chan Int) ; c2 <- newChan :: IO(Chan Int) ; forkIO (client c1 c2) ; forkIO (server c2 c1) }

Cse536 Functional Programming 13 6/30/2015 Client Server Example from chapt 14 client :: Chan Int -> Chan Int -> IO () client cin cout = do { writeChan cout 1 ; loop } where loop = do { c <- readChan cin ; print c ; writeChan cout c ; loop } server :: Chan Int -> Chan Int -> IO () server cin cout = do loop where loop = do { c <- readChan cin ; writeChan cout (c+1) ; loop }

Cse536 Functional Programming 14 6/30/2015 Rendering Reactive Animations To render a reactive animation, we need to connect the stream of real events (mouse clicks, key presses, clock ticks, etc.) to our abstract representation of behaviors as stream transformers. The Goal is to write a function: reactimate :: String -> Behavior a -> (a -> IO Graphic) -> IO () Since a (Behavior a) has form (Beh f) where f is a function with type ([Maybe UserAction],[Time]) -> [a] We need to manufacture a pair of streams with type ([Maybe UserAction],[Time])

Cse536 Functional Programming 15 6/30/2015 windowUser We do this with the function: windowUser :: Window -> IO ([Maybe UserAction],[Time],IO ()) Used in the following fashion ((uts,ts),addEvents) <- windowUser w

Cse536 Functional Programming 16 6/30/2015 The Channel Abstraction (us,ts,addEvents) <- windowUser w us, and ts are infinite streams made with channels. addEvents :: IO () is a action which adds the latest user actions, thus extending the streams us and ts

Cse536 Functional Programming 17 6/30/2015 Reactimate reactimate :: String -> Behavior a -> (a -> IO Graphic) -> IO () reactimate title franProg toGraphic = runGraphics $ do w <- openWindowEx title (Just (0,0)) (Just (xWin,yWin)) drawBufferedGraphic (Just 30) (us,ts,addEvents) <- windowUser w addEvents let drawPic (Just p) = do g <- toGraphic p setGraphic w g addEvents getWindowTick w drawPic Nothing = return () let Event fe = sample `snapshot_` franProg mapM_ drawPic (fe (us,ts))

Cse536 Functional Programming 18 6/30/2015 Making a Stream from a Channel makeStream :: IO ([a], a -> IO ()) makeStream = do ch <- newChan contents <- getChanContents ch return (contents, writeChan ch)

Cse536 Functional Programming 19 6/30/2015 A Reactive window windowUser :: Window -> IO ([Maybe UserAction], [Time], IO ()) windowUser w = do (evs, addEv) <- makeStream t0 <- timeGetTime let addEvents = let loop rt = do mev <- maybeGetWindowEvent w case mev of Nothing -> return () Just e -> addEv(rt, Just e) >> loop rt in do t <- timeGetTime let rt = w32ToTime (t-t0) loop rt addEv (rt, Nothing) return (map snd evs, map fst evs, addEvents)

Cse536 Functional Programming 20 6/30/2015 The “Paddle Ball” Game paddleball vel = walls `over` paddle `over` ball vel walls = let upper = paint blue (translate ( 0,1.7) (rec )) left = paint blue (translate (-2.2,0) (rec )) right = paint blue (translate ( 2.2,0) (rec )) in upper `over` left `over` right paddle = paint red (translate (fst mouse, -1.7) (rec )) between x (a,b) = x >* a &&* x <* b

Cse536 Functional Programming 21 6/30/2015 The “reactive” ball ball vel = let xvel = vel `stepAccum` xbounce ->> negate xpos = integral xvel xbounce = predicate (xpos >* 2 &&* xvel >* 0 ||* xpos <* -2 &&* xvel <* 0) yvel = vel `stepAccum` ybounce ->> negate ypos = integral yvel roofbounce = ypos >* 1.5 &&* yvel >* 0 paddlebounce = (ypos `between` (-2.0,-1.5)) &&* (fst mouse `between` (xpos-0.25,xpos+0.25)) &&* (yvel <* 0) ybounce = predicate (roofbounce ||* paddlebounce) in (paint yellow (translate (xpos, ypos) (ell )))