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.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Kathleen Fisher cs242 Reading: Tackling the Awkward Squad, Sections 1-2Tackling the Awkward Squad Real World Haskell, Chapter 7: I/OReal World Haskell.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
The IO Monad Mooly Sagiv Slides from John Mitchell Kathleen Fisher Simon Peyton Jones Reading: “Tackling the Awkward Squad” “Real World Haskell,” Chapter.
Kathleen Fisher cs242 Reading: “Tackling the Awkward Squad,” Sections 1-2Tackling the Awkward Squad “Real World Haskell,” Chapter 7: I/OReal World Haskell.
Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.
File AccessCS-2301, B-Term File Access CS-2301, System Programming for Non-Majors (Slides include materials from The C Programming Language, 2 nd.
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.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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)
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
Cse536 Functional Programming 1 6/30/2015 Lecture #16, Nov. 29, 2004 Todays Topics – Files, Channels, and Handles –IO exception handling –First Class Channels.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
CS510AP Quick Check Monads. QuickCheck Quick check is a Haskell library for doing random testing. You can read more about quickcheck at –
Today’s topic: –File operations –I/O redirection –Inter-process communication through pipes.
0 PROGRAMMING IN HASKELL Chapter 9 - Interactive Programs.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
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.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
Chapter 6 Writing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
Comp150PLD Reading: “Tackling the Awkward Squad,” Sections 1-2Tackling the Awkward Squad “Real World Haskell,” Chapter 7: I/OReal World Haskell Thanks.
Case Study - Fractions Timothy Budd Oregon State University.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
© 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.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
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!)
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
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.
Data in Haskell. What is data? Measurements of some kind stored in a computer. – Examples Simple: numbers, text, truth values … Structured: sequences,
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Exception Handling How to handle the runtime errors.
CPT: Chars/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to look at how C processes characters 4. Character.
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.
the IO Monad Kathleen Fisher cs242
PROGRAMMING IN HASKELL
Exceptions, Templates, and the Standard Template Library (STL)
Why exception handling in C++?
Haskell Chapter 9.
Part IX Fundamentals of C and C++ Programming Exception Handling
Control Structures – Selection
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Haskell Dealing with impurity 30-Nov-18.
Haskell Dealing with impurity 30-Nov-18.
Exception Handling Chapter 9 Edited by JJ.
Programming Assignment # 2 – Supplementary Discussion
Chapter 3: Input/Output
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Input and Output.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Haskell Dealing with impurity 8-Apr-19.
PROGRAMMING IN HASKELL
Grab Bag of Interesting Stuff
Programming Languages
Haskell Dealing with impurity 29-May-19.
Haskell Dealing with impurity 28-Jun-19.
Presentation transcript:

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 we investigate advanced IO ideas: file handles, channels, exceptions, and concurrency.  The ideas developed here will be used in the next chapter to write a renderer for FAL.  The ideas will continue to be cast in terms of “IO actions” of type “IO a”, and will be sequenced using Haskell’s “do” syntax.  The “mysteries” underlying the type “IO” and Haskell’s “do” syntax will be revealed in Chapter 18. (Guess what’s underneath it all? Yes, functions! )

File Handles  Recall from Chapter 3 the IO actions: writeFile:: FilePath -> String -> IO () appendFile:: FilePath -> String -> IO () type FilePath = String  These functions open a file, write a string, and then close the file.  But if many successive writes are needed, the repeated openings and closings can be very inefficient.  Better to open a file, and leave it open until done: openFile:: FilePath -> IOMode -> IO Handle hClose:: Handle -> IO () data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode

File Operations  Once open, many file operations are possible: hPutChar :: Handle -> Char -> IO () hPutStr :: Handle -> String -> IO () hPutStrLn :: Handle -> String -> IO () hPrint :: Show a => Handle -> a -> IO () hGetChar :: Handle -> IO Char hGetLine :: Handle -> IO String hGetContents :: Handle -> String when in “WriteMode” when in “ReadMode”

Standard Channels  As in many OS’s, certain kinds of IO are treated like files. In Haskell these are called channels, and include standard input (stdin), standard output (stdout), and standard error (stderr).  Indeed, these two functions are pre-defined in the Prelude: getChar :: IO Char getChar = hGetChar stdin putChar :: IO () putChar = hPutChar stdout

Exceptions  There are many ways that an IO action might fail, and we need a way to detect and recover from such failures.  In Haskell, IO failures are called exceptions, and they can be “caught” by: catch :: IO a -> (IOError -> IO a) -> IO a  For example: getChar' :: IO Char getChar' = catch getChar (\e -> return '\n')

Dispatching on IOError  IoError is an abstract type with predicates such as: isEOFError :: IOError -> Bool isDoesNotExistError :: IOError -> Bool and a “throw” operation: ioError :: IOError -> IO a  A “more refined” getChar can then be defined: getChar' :: IO Char getChar' = catch getChar (\e -> if isEOFError e then return '\n‘ else ioError e ) Note how ioError “throws” the error to an outer dynamic scope.  (See text for example of “nested” exceptions.)

Putting It All Together (copying a file) getAndOpenFile :: String -> IOMode -> IO Handle getAndOpenFile prompt mode = do putStr prompt name do putStrLn ("Cannot open " ++ name) print error getAndOpenFile prompt mode ) Main :: IO () main = do fromHandle <- getAndOpenFile "Copy from: " ReadMode toHandle <- getAndOpenFile "Copy to: " WriteMode contents <- hGetContents fromHandle hPutStr toHandle contents hClose fromHandle hClose toHandle putStrLn "Done."

First-Class Channels  “First-class channels” are different from the “standard channels” described earlier.  They are a mechanism through which Haskell “processes” can communicate asynchronously.  A first-class channel containing values of type “a” has type “Chan a”.  The key operations are: newChan:: IO (Chan a) writeChan:: Chan a -> a -> IO () readChan:: Chan a -> IO a getChanContents:: Chan a -> IO [a] isEmptyChan:: Chan a -> IO Bool

Example  A first-class channel implements an unbounded queue that can be written to and read from asynchronously.  For example: do c <- newChan writeChan c `a` writeChan c `b`... do... a <- readChan c b <- readChan c return [a,b] returns the string "ab".

Concurrency  Concurrent processes may be forked off from the main computation by forkIO :: IO () -> IO ()  The IO action: forkIO p will cause p to run concurrently with the main program.  For example, we can create a concurrent version of the client-server program from Chapter 14. [ see next slide ]

Concurrent Client-Server 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 main :: IO () main = do c1 <- newChan :: IO (Chan Int) c2 <- newChan :: IO (Chan Int) forkIO (client c1 c2) forkIO (server c2 c1)