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.

Slides:



Advertisements
Similar presentations
Cse536 Functional Programming 1 1/13/2015 Lecture #13, Nov. 08, 2004 Today’s Topics –Simple animations –Buffered graphics –Animations in Haskell –Complex.
Advertisements

RAPTOR Syntax and Semantics By Lt Col Schorsch
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
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
Important Irvine Library Procedures Randomize Randomize –Initializes the seed of the random-number formula by both the Random32 and the RandomRange procedures.
Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.
Cse536 Functional Programming 1 6/11/2015 Lecture #5, Oct 11, 2004 Reading Assignments –Finish Chapter 3, Simple Graphics –Read Chapter 4, Shapes II, Drawing.
Chapter 4 Shapes II: Drawing Shapes. Recall the Shape Datatype data Shape = Rectangle Side Side | Ellipse Radius Radius | RtTriangle Side Side | Polygon.
Chapter 2: Algorithm Discovery and Design
Introduction to Computer Science Exam Information Unit 20.
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.
CS 201 Functions Debzani Deb.
Programming 1 Tim Sheard. Spring Quarter Goals of the class – Learn to write simple programs using the programming language Haskell. – Learn by example.
A Simple Applet. Applets and applications An applet is a Java program that runs on a web page –Applets can be run from: Internet Explorer Netscape Navigator.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
Chapter 5 Polymorphic and Higher-Order Functions.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
CS510AP Quick Check Monads. QuickCheck Quick check is a Haskell library for doing random testing. You can read more about quickcheck at –
Chapter 2: Algorithm Discovery and Design
0 PROGRAMMING IN HASKELL Chapter 9 - Interactive Programs.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C - Input & Output When we are saying Input that means to feed some data into program. This can be given in the form of file or from command line. C programming.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Lecture 5: Interaction 1  Principles of Interactive Graphics  CMSCD2012  Dr David England, Room 711,  ex 2271 
Haskell Chapter 8. Input and Output  What are I/O actions?  How do I/O actions enable us to do I/O?  When are I/O actions actually performed?
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 5 – Dental Payment Application: Introducing.
Fundamentals of Python: First Programs
The LC-3 – Chapter 7 COMP 2620 Dr. James Money COMP
Programming for Artists ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 10 Fall 2010.
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
Loops & Graphics IP 10 Mr. Mellesmoen Recall Earlier we wrote a program listing numbers from 1 – 24 i=1 start: TextWindow.WriteLine(i) i=i+1 If.
© 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.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Chapter-4 Managing input and Output operation.  Reading, processing and writing of data are three essential functions of a computer program.  Most programs.
CSC 1010 Programming for All Lecture 7 Input, Output & Graphics.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
C OMPUTER P ROGRAMMING 1 Input and Variables. I/O S TATEMENTS : I NPUT & V ARIABLES Input is the term used to describe the transfer of information from.
Data in Haskell. What is data? Measurements of some kind stored in a computer. – Examples Simple: numbers, text, truth values … Structured: sequences,
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
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.
Haskell Chapter 8.
Theory of Computation Lecture 4: Programs and Computable Functions II
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Haskell Dealing with impurity 30-Nov-18.
Haskell Dealing with impurity 8-Apr-19.
PROGRAMMING IN HASKELL
Grab Bag of Interesting Stuff
Programming Languages
Computer Science 312 I/O and Side Effects 1.
Theory of Computation Lecture 4: Programs and Computable Functions II
Haskell Dealing with impurity 29-May-19.
Haskell Dealing with impurity 28-Jun-19.
Basic shell scripting CS 2204 Class meeting 7
getline() function with companion ignore()
Advanced Functional Programming
Presentation transcript:

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 for their values.  But sometimes we want our programs to effect the real world (printing, controlling a robot, drawing a picture, etc).  How do we reconcile these two competing properties?  In Haskell, “pure values” are separated from “worldly actions”, in two ways: Types: An expression with type IO a has possible actions associated with its execution, while returning a value of type a. Syntax: The do syntax performs an action, and (using layout) allows one to sequence several actions.

Sample Effects or Actions State Intuitively, some programs have state that changes over time. Exceptions There may be an error instead of a final value Non-determinism There may be multiple possible final values Communication There may be external influence on the computation Perform some Input or Output, as well as a final value. E.g., draw graphics on a display

The do Syntax  Let act be an action with type IO a.  Then we can perform act, retrieve its return value, and sequence it with other actions, by using the do syntax: do val <- act the next action the action following that return x -- final action may return a value  Note that all actions following val <- act can use the variable val.  The function return takes a value of type a, and turns it into an action of type IO a, which does nothing but return the value.

do Syntax Details :: Integer:: IO Integer :: IO () (actions without “v <- …” usually have this type) :: IO Integer (the type of the last action also determines the type of the entire do expression) :: Char :: IO Char do x <- f 5 c <- getChar putChar c return (x + 4)

When IO Actions are Performed  A value of type IO a is an action, but it is still a value: it will only have an effect when it is performed.  In Haskell, a program’s value is the value of the variable main in the module Main. If that value has type IO a, then it will be performed, since it is an action. If it has any other type, its value is simply printed on the display.  In Hugs, however, you can type any expression to the Hugs prompt. E.g., for main above, if the expression has type IO a it will be performed, otherwise its value will be printed on the display.

Predefined IO Actions -- get one character from keyboard getChar :: IO Char -- write one character to terminal putChar :: Char -> IO () -- get a whole line from keyboard getLine :: IO String -- read a file as a String readFile :: FilePath -> IO String -- write a String to a file writeFile :: FilePath -> String -> IO ()

Recursive Actions getLine can be defined recursively in terms of simpler actions: getLine :: IO String getLine = do c <- getChar -- get a character if c == '\n' -- if it’s a newline then return "" -- then return empty string else do l <- getLine –- otherwise get rest of -- line recursively, return (c:l) -- and return entire line

Example: Unix wc Command  The unix wc (word count) program reads a file and then prints out counts of characters, words, and lines.  Reading the file is an action, but computing the information is a pure computation.  Strategy: Define a pure function that counts the number of characters, words, and lines in a string. number of lines = number of ‘\n’ number of words ~= number of ‘ ’ plus number of ‘\t’ Define an action that reads a file into a string, applies the above function, and then prints out the result.

Implementation wcf :: (Int,Int,Int) -> String -> (Int,Int,Int) wcf (cc,w,lc) [] = (cc,w,lc) wcf (cc,w,lc) (' ' : xs) = wcf (cc+1,w+1,lc) xs wcf (cc,w,lc) ('\t' : xs) = wcf (cc+1,w+1,lc) xs wcf (cc,w,lc) ('\n' : xs) = wcf (cc+1,w+1,lc+1) xs wcf (cc,w,lc) (x : xs) = wcf (cc+1,w,lc) xs wc :: IO () wc = do name <- getLine contents <- readFile name let (cc,w,lc) = wcf (0,0,0) contents putStrLn (“The file: “ ++ name ++ “has “) putStrLn (show cc ++ “ characters “) putStrLn (show w ++ “ words “) putStrLn (show lc ++ “ lines “)

Example Run Main> wc elegantProse.txt The file: elegantProse.txt has 2970 characters 1249 words 141 lines Main> I typed this.

Graphics Actions  Graphics windows are traditionally programmed using commands; i.e. actions.  Some graphics actions relate to opening up a graphics window, closing it, etc.  Others are associated with drawing lines, circles, text, etc.

“Hello World” program using Graphics Library import SOEGraphics main0 = runGraphics $ do w <- openWindow "First window" (300,300) drawInWindow w (text (100,200) "hello world") k <- getKey w closeWindow w This imports a library, SOEGraphics, which contains many functions

Graphics Operators  openWindow :: String -> Point -> IO Window Opens a titled window of a particular size.  drawInWindow :: Window -> Graphic -> IO () Displays a Graphic value in a given window. Note that the return type is IO ().  getKey :: Window -> IO Char Waits until a key is pressed and then returns the character associated with the key.  closeWindow :: Window -> IO () Closes the window (duh…).

Mixing Graphics IO with Terminal IO spaceClose :: Window -> IO () spaceClose w = do k <- getKey w if k == ' ' then closeWindow w else spaceClose w main1 = runGraphics $ do w <- openWindow "Second Program" (300,300) drawInWindow w (text (100,200) “Hello Again") spaceClose w

Drawing Primitive Shapes  The Graphics libraries contain simple actions for drawing a few primitive shapes. ellipse :: Point -> Point -> Graphic shearEllipse :: Point -> Point -> Point -> Graphic line :: Point -> Point -> Graphic polygon :: [Point] -> Graphic polyline :: [Point] -> Graphic  From these we will build much more complex drawing programs.

Coordinate System (0,0) Increasing x-axis Increasing y-axis

Colors withColor :: Color -> Graphic -> Graphic data Color = Black | Blue | Green | Cyan | Red | Magenta | Yellow | White

Example Program main2 = runGraphics $ do w <- openWindow "Draw some shapes" (300,300) drawInWindow w (ellipse (0,0) (50,50)) drawInWindow w (shearEllipse (0,60) (100,120) (150,200)) drawInWindow w (withColor Red (line (200,200) (299,275))) drawInWindow w (polygon [(100,100),(150,100),(160,200)]) drawInWindow w (withColor Green (polyline [(100,200),(150,200), (160,299),(100,200)])) spaceClose w

The Result ; drawInWindow w (ellipse (0,0) (50,50)) ; drawInWindow w (shearEllipse (0,60) (100,120) (150,200)) ; drawInWindow w (withColor Red (line (200,200) (299,275))) ; drawInWindow w (polygon [(100,100), (150,100), (160,200)]) ; drawInWindow w (withColor Green (polyline [(100,200),(150,200), (160,299),(100,200)]))

More Complex Programs  We’d like to build bigger programs from these small pieces.  For example: Sierpinski’s Triangle – a fractal consisting of repeated drawing of a triangle at successively smaller sizes.  As before, a key idea is separating pure computation from graphics actions.

Geometry of One Triangle size 2 + size 2 = hyp 2 Remember that y increases as we go down the page hyp (x+size/2,y-size/2) (x,y-size) (x,y-size/2) (x,y)(x+size,y) (x+size/2,y)

Draw 1 Triangle fillTri x y size w = drawInWindow w (withColor Blue (polygon [(x,y), (x+size,y), (x,y-size)])) minSize = 8 (x,y)size

sierpinskiTri w x y size = if size <= minSize then fillTri x y size w else let size2 = size `div` 2 in do sierpinskiTri w x y size2 sierpinskiTri w x (y-size2) size2 sierpinskiTri w (x+size2) y size2 main3 = runGraphics $ do w <- openWindow "Sierpinski's Tri" (400,400) sierpinskiTri w spaceClose w Sierpinski’s Triangle (x,y-size) (x,y-size/2) (x,y) (x+size,y)(x+size/2,y)