two

  • Published on
    06-Jan-2016

  • View
    35

  • Download
    1

DESCRIPTION

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 - PowerPoint PPT Presentation

Transcript

  • twomotion and change: programming with imperatives

  • OverviewReviewImperative ProgrammingMore on objectsAppendix

  • The story up until nowEverything in your computer is dataIncluding programs

    Data is divided into objectsObjects can be inside of other objectsBoxes inside groupsColors inside bitmaps

    Objects have typesProceduresNumbers (1, -3.5)Strings (this is a string, blue)BitmapsPicture objects (lines, groups, boxes, etc.)

  • The story up until nowComputation is performed using expressionsExpressions have (or return) values (i.e. outputs)Computation is performed by recursively replacing expressions with their values

    A computations only output is its return valueIts return value depends onThe expressions structureThe other definitions in the programIt doesnt depend on what was computed before

  • Review: rules for executionLook at the expressionIf its a number or stringIts its own valueIf its a name (i.e. a word)Look its value up in the dictionary

    (Check if its one of the special cases from the next slide)

    Otherwise its a procedure call[proc-expression arg-expression1 arg-expressionn]Execute all the subexpressions (proc-expression and arg-expression1 through arg-expressionn )Run the value of, passing it the values of proc-expression , passing it the values of arg-expression1 through arg-expressionn as inputsUse its output as the value of the expressionThese rules are worth memorizing

  • Special casesIf it starts with define[define name value-expression]Run value-expressionAssign its value to name in the dictionary

    If it starts with the words with or with*[with name1 = value-expression1 namelast = value-expressionlast result-expression]Run the value-expressionsAssign their values to their respective names in the dictionaryRun result-expressionSet the dictionary back the way it wasReturn the value from result-expression

    If it has a inside it[name1 namelast result-expression]Make a procedureThat names its inputs name1 namelastAnd returns the value of result-expression (presumably using those names)

    If it starts with if[if test-expression result-expression alternative-expression]Run test-expressionIf it returns trueRun result-expression and return its valueOtherwise,Run alternative-expression and return its value

  • OverviewReviewImperative ProgrammingMore on objectsAppendix

  • Change and effectBut some expressions dont really return values[define name value] Happens to print out value when you run it, but thats 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 typeNot because they return valuesBut because they do thingsThey change the computer

    These changes are called side effects, or just effectsWhat it really means is change caused by the expression

  • Calling procedures for their effectsYou can write procedures that make a wide range of changes in the computerChanging a variables value (aka assignment)Changing a data object (aka mutation)Creating filesCreating windowsPerforming input or output

    As with everything else in this class,Complex effectsAre ultimately built up from a few kinds of simple effectsAnd methods for combining them

  • Assignment statementsThe simplest change primitive is [name new-value]After execution, the variable name is changed to have the value new-valueVariable must have already been created using define, with, or

    Why is this different from define?Define declares an entirely new variable, it doesnt change existing variablesOkay, I know sometimes it does change existing variables, but thats just a klugeWell see the difference in a moment

  • Changing a global variable[define count 0]

    [define increment! [ [count [+ count 1]]]]

    [define clear! [ [count 0]]]> count0> [increment!]

    > count1> [clear!]

    > count0>

  • SequencingChanges are most useful when we can chain them together

    That means we need some way of specifying thatWe want to do several things in a rowAnd we want them done in a specific order

  • Sequencing with proceduresProcedures can specify a series of expressions to run [args expression expression][define [name args ] expression expression]

    The expressions are run in order, first to lastTheir return values are ignoredExcept for the last expressionProcedures 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]]> count0> [increment!]1> count1> [clear!]0> count0>

  • Iteration (aka looping) so farSo far, when weve wanted to do something repeatedly, weveWritten the something as a procedureCall another procedure that iterates and passed our procedure to it as an argumentSo 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 primitiveMost imperative languages have special constructs for iteration

    The most basic is the while loop[while test expressions ]

    Means:Run testIf its true, run expressionsAnd 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 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer1position1

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer1position1

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer3position1

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer3position2

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer3position2

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer6position2

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer6position3

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer6position3

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer10position3

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer10position4

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer10position4

  • Example: [fold + [list 1 2 3 4]][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]]]VarValueproc+list[1 2 3 4]answer10position4

  • 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 1 2 3 4]]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 1 2 3 4]]Error: Index was outside the bounds of the array.VarValueproc+list[1 2 3 4]answer8position4

  • 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 1 2 3 4]]Error: Index was outside the bounds of the array.VarValueproc+list[1 2 3 4]answer8position4

  • Functional programmingversus imperative programmingFunctional programming is programming without effects and sequencingValue of a procedure call is determined entirely by the procedures argumentsValue of an expression depends only on the computations involved in computing its arguments

    Imperative programmingValue of a procedure call can potentially be changed by any of the preceding steps of the computationEven if they seem unrelated

  • Functional programmingversus imperative programmingFunctional programming is programming without effects and sequencingOnly output from a procedure is its return valueProcedures behave like clauses in English (or functions in math)Computation is achieved by nesting procedure callsWe think about execution in terms of call and response, transformation, and the other metaphors we discussed last quarter

    Imperative programmingOutput of a procedure is its effect on the computerComputation is achieved by sequencing effectsWe think about execution in terms of changes and motion

  • Fold in functional an imperative formFunctional 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 listAlso, these two versions dont do exactly the same thingThey process the elements of the list in opposite ordersBut theyre easier to understand this wayImperative 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 formFunctional 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 programmingImperative programs can be more efficient than functional programs

    Sometimes it really is simplerSimulationsWhat youre computing just is a series of changesThe changes the simulated system would have madeImperative style is much more naturalDirectly expresses changeExample: video gamesUsing random numbersIf your random number procedure always returns the same value, it isnt very usefulOther applications where the task definition involves change

  • OverviewReviewImperative ProgrammingMore on objectsAppendix

  • Looking inside data objects Data objects are like formsThey have fields (aka members)Filled in by values

    The fieldsHave names (Width, Height)The fields are filled in by other data objects

    The objects type (Box, Color) determines what fields it hasNumberValue: 10BoxWidth: 10Height: 10EllipseWidth: 15Height: 10ProcedureName: iterated-groupArguments: proc countBody: [apply group [up-to count proc]]ColorR: 240G: 220B: 0

  • Member notationYou can ask for a field of a data object using the . notation: object.memberNamemyColor.R[pixel myBitmap 0 0].Riterated-group.Nameiterated-group.Argumentsmybox.Width

    Note: to simplify the presentation, Ive 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.NumberValue: 10BoxWidth: 10Height: 10EllipseWidth: 15Height: 10ProcedureName: iterated-groupArguments: proc countBody: [apply group [up-to count proc]]ColorR: 240G: 220B: 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-valueObject 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 theyre 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 callsAll 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 x1 y1 x2 y2]

  • 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 dont yet know enough to understand what this is doing, so dont sweat it.

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

  • OverviewReviewImperative ProgrammingMore on objectsAppendix

  • begin expressionsAnother way of sequencing effects

    [begin expression ]Execute each expression, in orderAgain, all return values are ignoredExcept for the lastWhich is returned as the value of the begin expression

Recommended

View more >