Two motion and change: programming with imperatives.

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Chapter 4 Computation Bjarne Stroustrup
Introduction to C Programming
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
CS0007: Introduction to Computer Programming
Introduction to Recursion and Recursive Algorithms
MATH 224 – Discrete Mathematics
RAPTOR Syntax and Semantics By Lt Col Schorsch
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Three types, subtypes, and inheritance. The story up until now Everything in your computer is data Including programs Data is divided into objects Objects.
Chapter 10 Introduction to Arrays
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Six compound procedures and higher-order procedures.
Chapter 20 Thinking Big: Functions. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Anatomy of a Function Functions are packages for.
Sixteen lists and compound data. Recap Names: constants and variables When evaluated, return a specific data objects Can make new names with: [define.
Program Design and Development
Fourteen lists and compound data. Some primitive data types Integers (whole numbers) 1, 2, 3, -1, 0, , etc. “Floating-point” numbers ,
Loops – While, Do, For Repetition Statements Introduction to Arrays
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Seven constructing simple procedures using abstraction.
Computer Science 1620 Programming & Problem Solving.
Thirteen conditional expressions: letting programs make “decisions”
Six compound procedures and higher-order procedures.
Programming Epson Robots – Part 2 ME 4135 – Fall 2012 Dr. R. Lindeke.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Games and Simulations O-O Programming in Java The Walker School
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
If statements while loop for loop
CPS120: Introduction to Computer Science Decision Making in Programs.
The Loop Macro Many of the CL “functions” are actually macros (let, progn, if, etc) The most complicated macro in CL is probably the Loop macro –The Loop.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
BY A Mikati & M Shaito Awk Utility n Introduction n Some basics n Some samples n Patterns & Actions Regular Expressions n Boolean n start /end n.
I Power Higher Computing Software Development High Level Language Constructs.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
INVITATION TO Computer Science 1 11 Chapter 2 The Algorithmic Foundations of Computer Science.
Controlling Program Flow with Decision Structures.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
CISC105 – General Computer Science Class 4 – 06/14/2006.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Comp1004: Loops and Arrays I Whiles, For and Arrays[]
Introduction To Repetition The for loop
constructing simple procedures using abstraction
Primitive Data, Variables, Loops (Maybe)
JavaScript Functions.
Java Programming: Guided Learning with Early Objects
Conditions and Ifs BIS1523 – Lecture 8.
Understanding the Three Basic Structures
What would be our focus ? Geometry deals with Declarative or “What is” knowledge. Computer Science deals with Imperative or “How to” knowledge 12/25/2018.
Introduction to Problem Solving and Control Statements
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
What would be our focus ? Geometry deals with Declarative or “What is” knowledge. Computer Science deals with Imperative or “How to” knowledge 2/23/2019.
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Classes, Objects and Methods
The structure of programming
CSC1401 Manipulating Pictures 2
Thinking procedurally
Presentation transcript:

two motion and change: programming with imperatives

Overview Review Imperative Programming More on objects Appendix

The story up until now Everything in your computer is data Including programs Data is divided into objects Objects can be “inside” of other objects Boxes inside groups Colors inside bitmaps Objects have types Procedures Numbers (1, -3.5) Strings (“this is a string”, “blue”) Bitmaps Picture objects (lines, groups, boxes, etc.)

The story up until now Computation is performed using expressions Expressions have (or “return”) values (i.e. outputs) Computation is performed by recursively replacing expressions with their values A computation’s only output is its return value It’s return value depends on The expression’s structure The other definitions in the program It doesn’t depend on what was computed before

Review: rules for execution Look at the expression If it’s a number or string It’s its own value If it’s a name (i.e. a word) Look its value up in the dictionary (Check if it’s one of the special cases from the next slide) Otherwise it’s a procedure call [proc-expression arg-expression 1 … arg-expression n ] Execute all the subexpressions (proc-expression and arg-expression 1 through arg-expression n ) Run the value of, passing it the values of proc-expression, passing it the values of arg-expression 1 through arg-expression n as inputs Use its output as the value of the expression These rules are worth memorizing

Special cases If it starts with define [define name value-expression] Run value-expression Assign its value to name in the dictionary If it starts with the words with or with* [with name 1 = value-expression 1 … name last = value-expression last result-expression] Run the value-expressions Assign their values to their respective names in the dictionary Run result-expression Set the dictionary back the way it was Return the value from result-expression If it has a → inside it [name 1 … name last → result-expression] Make a procedure That names its inputs name 1 … name last And returns the value of result-expression (presumably using those names) If it starts with if [if test-expression result-expression alternative-expression] Run test-expression If it returns true Run result-expression and return its value Otherwise, Run alternative-expression and return its value

Overview Review Imperative Programming More on objects Appendix

Change and effect But some expressions don’t really return values [define name value] Happens to print out value when you run it, but that’s not the point. [using package] (e.g.: [using Examples.Stacking]) Returns something cryptic but irrelevant; what matters is that it causes a bunch of procedures to become defined These are examples of expressions we type Not because they return values But because they do things They change the computer These changes are called side effects, or just effects What it really means is change caused by the expression

Calling procedures for their effects You can write procedures that make a wide range of changes in the computer Changing a variable’s value (aka assignment) Changing a data object (aka mutation) Creating files Creating windows Performing input or output As with everything else in this class, Complex effects Are ultimately built up from a few kinds of simple effects And methods for combining them

Assignment statements The simplest change primitive is “←” [name ← new-value] After execution, the variable name is changed to have the value new-value Variable must have already been “created” using define, with, or Why is this different from define? Define declares an entirely new variable, it doesn’t change existing variables Okay, I know sometimes it does change existing variables, but that’s just a kluge We’ll see the difference in a moment

Changing a global variable [define count 0] [define increment! [→ [count ← [+ count 1]]]] [define clear! [→ [count ← 0]]] > count 0 > [increment!] > count 1 > [clear!] > count 0 >

Sequencing Changes are most useful when we can chain them together That means we need some way of specifying that We want to do several things in a row And we want them done in a specific order

Sequencing with procedures Procedures can specify a series of expressions to run [args … → expression … expression] [define [name args …] expression … expression] The expressions are run in order, first to last Their return values are ignored Except for the last expression Procedure’s return value is the value of the last expression

Changing a global variable [define count 0] [define increment! [→ [count ← [+ count 1]] count]] [define clear! [→ [count ← 0] count]] > count 0 > [increment!] 1 > count 1 > [clear!] 0 > count 0 >

Iteration (aka looping) so far So far, when we’ve wanted to do something repeatedly, we’ve Written the something as a procedure Call another procedure that iterates and passed our procedure to it as an argument So forms of iteration are represented by specialized procedures [filter beatles? list] [map album-title [filter beatles? list]] [fold + list] [iterated-group [n → [box [× n 2] [× n 2]]] 10]

Looping as a sequencing primitive Most imperative languages have special constructs for iteration The most basic is the while loop [while test expressions …] Means: Run test If it’s true, run expressions And run test again, etc, Keep going until test is false

Fold in imperative form [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]]

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ]

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer1 position1

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer1 position1

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer3 position1

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer3 position2

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer3 position2

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer6 position2

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer6 position3

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer6 position3

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer10 position3

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer10 position4

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer10 position4

Example: [fold + [list ]] [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] «Return the accumulated answer» answer]]] VarValue proc+ list[ ] answer10 position4

Programming with effects can be tricky ► [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [position ← [+ position 1]] [answer ← [proc answer [get list position]]]] «Return the accumulated answer» answer]]] ► [fold + [list ]] Error: Index was outside the bounds of the array. ►

What happened? ► [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [position ← [+ position 1]] [answer ← [proc answer [get list position]]]] «Return the accumulated answer» answer]]] ► [fold + [list ]] Error: Index was outside the bounds of the array. ► VarValue proc+ list[ ] answer8 position4

What happened? ► [define fold [proc list → «Make some variables» [with answer = [first list] position = 1 «Loop over all the elements of the list» [while [< position [length list]] «Fold in one more element» [position ← [+ position 1]] [answer ← [proc answer [get list position]]]] «Return the accumulated answer» answer]]] ► [fold + [list ]] Error: Index was outside the bounds of the array. ► VarValue proc+ list[ ] answer8 position4

Functional programming versus imperative programming Functional programming is programming without effects and sequencing Value of a procedure call is determined entirely by the procedure’s arguments Value of an expression depends only on the computations involved in computing its arguments Imperative programming Value of a procedure call can potentially be changed by any of the preceding steps of the computation Even if they seem unrelated

Functional programming versus imperative programming Functional programming is programming without effects and sequencing Only output from a procedure is its return value Procedures behave like clauses in English (or functions in math) Computation is achieved by nesting procedure calls We think about execution in terms of call and response, transformation, and the other metaphors we discussed last quarter Imperative programming Output of a procedure is its effect on the computer Computation is achieved by sequencing effects We think about execution in terms of changes and motion

Fold in functional an imperative form Functional version: [define fold [proc list → [if [= [length list] 1] [first list] [proc [first list] [fold proc [rest list]]]]]] Notes: The functional version uses recursion (remember recursion?) And it uses the rest procedure, which returns all but the first element of a list Also, these two versions don’t do exactly the same thing They process the elements of the list in opposite orders But they’re easier to understand this way Imperative version: [define fold [proc list → [with answer = [first list] position = 1 [while [< position [length list]] [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] answer]]]

Fold in functional an imperative form Functional version: [define fold [proc list → [if [= [length list] 1] [first list] [proc [first list] [fold proc [rest list]]]]]] More focused on what to compute (at least some people think so) Imperative version: [define fold [proc list → [with answer = [first list] position = 1 [while [< position [length list]] [answer ← [proc answer [get list position]]] [position ← [+ position 1]]] answer]]] More focused on how to compute it

Advantages of imperative programming Imperative programs can be more efficient than functional programs Sometimes it really is simpler Simulations What you’re computing just is a series of changes The changes the simulated system would have made Imperative style is much more natural Directly expresses change Example: video games Using random numbers If your random number procedure always returns the same value, it isn’t very useful Other applications where the task definition involves change

Overview Review Imperative Programming More on objects Appendix

Number Value: 10 Looking inside data objects Data objects are like forms They have fields (aka members) Filled in by values The fields Have names (Width, Height) The fields are filled in by other data objects The object’s type (Box, Color) determines what fields it has Box Width: 10 Height: 10 Ellipse Width: 15 Height: 10 Procedure Name: iterated-group Arguments: proc count Body: [apply group [up-to count proc]] Color R: 240 G: 220 B: 0

Number Value: 10 Member notation You can ask for a field of a data object using the “.” notation: object.memberName myColor.R [pixel myBitmap 0 0].R iterated-group.Name iterated-group.Arguments mybox.Width Note: to simplify the presentation, I’ve lied here about what the actual fields of boxes, procedures, etc. are. You can find out what fields are really in an object using the inspector. Box Width: 10 Height: 10 Ellipse Width: 15 Height: 10 Procedure Name: iterated-group Arguments: proc count Body: [apply group [up-to count proc]] Color R: 240 G: 220 B: 0

Generalized assignment (aka mutation) You can also change fields of an object using “←” [object.member-name ← new-value] After execution, the field member-name of object is changed to have the value new-value Object may be any expression (not just a variable) Examples [myColor.R ← 7] [myPen.Brush.Color.R ← 7] [form.Text ← “This is a the title of this window”]

Member procedures (aka methods) A lot of procedures are stored “inside” of objects You access them like any other members, except they’re procedures so you can call them [object.member arg … arg] Examples [someobject.ToString] Converts someobject into a string that (hopefully) is descriptive of the object. [Directory.GetFiles “c:/”] Returns a list of all the files in the specified directory (C:\, in this case)

Example: windows graphics calls All things you can draw on in MS Windows are objects of type “Graphics” The have many members, but here are some useful methods: [object.DrawLine pen start end] [object.DrawEllipse pen x 1 y 1 x 2 y 2 ]

Some magic for making a window [define with-window [name proc → [with w = [new Form] [w.Text ← name] [w.Show] [proc [w.CreateGraphics]] [Application.Run w]]]] As with iterated-group, when we first gave it to you, you don’t yet know enough to understand what this is doing, so don’t sweat it.

Imperative drawing using methods [with-window “test” [g → [g.DrawLine [pen “black” 1] [point 0 0] [point ]] [g.DrawLine [pen “blue” 3] [point 50 0] [point ]] [g.DrawEllipse [pen “red” 40] ]]]

Overview Review Imperative Programming More on objects Appendix

begin expressions Another way of sequencing effects [begin expression …] Execute each expression, in order Again, all return values are ignored Except for the last Which is returned as the value of the begin expression