Unit 6:   Teaching Functions to Compare

imageUnit 6Teaching Functions to Compare
Unit Overview

Students discover Boolean types, and use them to create programs that test values, and then model scenarios using these programs.

Agenda

Product Outcomes:
  • Students detect when game elements have moved offscreen (so they can reappear on the other edge of the screen)

Standards and Evidence Statements:

Standards with prefix BS are specific to Bootstrap; others are from the Common Core. Mouse over each standard to see its corresponding evidence statements. Our Standards Document shows which units cover each standard.

  • 7.EE.3-4: The student uses numerical and algebraic expressions and equations to solve real-life and mathematical problems

    • use of positive and negative rational numbers in any form (whole numbers, fractions, and decimals) to solve multi-step real-life and mathematical problems

    • estimation of answers using mental computation to assess the reasonableness of solutions

    • use of variables to represent quantities in a real-world or mathematical problem

    • construction of simple equations and inequalities to solve problems by reasoning about the quantities

    • interpretation in context of solutions of word problems leading to inequalities

  • 8.F.1-3: The student defines, evaluates, and compares functions

    • description of a function as a rule that assigns to each input exactly one output

  • A-CED.1-4: The student solves equations and inequalities in one or more variable that describe numbers or relationships

    • creation of equations and inequalities in one variable, including linear and quadratic functions, and simple radical and exponential functions

  • A-SSE.1-2: The student interprets the structure of expressions to solve problems in context

    • manipulation of the structure of an expression, for example, writing x4 _ y4 as a difference of squares

  • F-IF.1-3: The student uses function notation to describe, evaluate, and interpret functions in terms of domain and range

    • description of a function using terms domain and range

  • F-IF.4-6: The student interprets the behavior of functions that arise in applications in terms of the context

    • interpretation of a relationship between two quantities in a table or graph in terms of key features

    • relation of the domain of a function to its graph and, where applicable, to the quantitative relationship it describes

  • BS-DR.2: The student can derive test cases for a given contract and purpose statement

    • given a Contract and a Purpose Statement, write multiple examples or test cases

    • given multiple examples, identify patterns in order to label and name the variables

  • BS-DR.3: Given mutiple test cases, the student can define a function

    • given examples and labeled variable(s), define the function

  • BS-IDE: The student is familiar with using a REPL, entering expressions properly, and interpreting error messages

    • enter and evaluate expressions on the computer

  • BS-PL.1: The student is familiar with declaring values and applying built-in functions using the programming language

    • representing (numeric, string, boolean, or image) values in the programming language

  • BS-PL.2: The student is comfortable using and writing Contracts for built-in functions

    • representing a function’s input and output using a contract

    • using a function by refering to its contract

Length: 90 minutes
Glossary:
  • boolean: a type of data with two values: true and false

  • contract: a statement of the name, domain, and range of a function

  • evaluate: perform the computation in an expression, producing an answer

  • string: any sequence of characters between quotation marks (examples: "hello", "42", "this is a string!")

Materials:
  • Pens/pencils for the students, fresh whiteboard markers for teachers

  • Class poster (List of rules, language table, course calendar)

  • Language Table (see below)

  • Student workbook

Preparation:

Types

Functions

Number

+ - * / sqr sqrt expt

String

string-append string-length

Image

rectangle circle triangle ellipse star text scale rotate put-image


Review

Overview

Learning Objectives

    Evidence Statements

      Product Outcomes

        Materials

        • Pens/pencils for the students, fresh whiteboard markers for teachers

        • Class poster (List of rules, language table, course calendar)

        • Language Table (see below)

        Preparation

        Review (Time 15 minutes)

        • What datatypes have you seen so far? Can you think of Number values? String values? Image values? What are some expressions that evaluate to a Number? How about the other datatypes?

          Before introducing a new datatype (Booleans), this would be a good time to quickly review the three major contexts students have learned for working with expressions: Circles of Evaluation, Contracts and Design Recipe. In this lesson, students will apply each one of them to Booleans, discovering that everything they’ve already learn still applies - even in the new type.

        Booleans

        Overview

        Students are introduced to a new type (Boolean), and practice using it with Circles of Evaluation, Contracts and Code.

        Learning Objectives

        • Students learn about Boolean values and functions that manipulate them

        Evidence Statements

        • Students will know the two Boolean values (true and false)

        • Students will write Circles of Evaluation for Boolean-producing functions

        • Students learn how to use arithmetic operators (like < and >) that produce Booleans

        Product Outcomes

          Materials

          • Pens/pencils for the students, fresh whiteboard markers for teachers

          • Class poster (List of rules, language table, course calendar)

          • Language Table (see below)

          Preparation

            Booleans (Time 10 minutes)

            • What would each of the following expressions evaluate to? (If you’re not sure, you can type it in and try it out!)

              • (+ 1 4)

              • (/ 4 2)

              • (circle 10 "solid" "blue")

              • (< 3 4)

            • The last expression, (< 3 4), uses a new function that compares Numbers, returning true if 3 is less than 4. What do you think it would return if the numbers were swapped?

              The function < tests if one number is less than another. Can you think of some other tests? Try them out in the Interactions window.

              Functions like <, > and = all consume two Numbers as their Domain, and produce a special value called a Boolean as their Range. Booleans are answers to a yes-or-no question, and Boolean functions are used to perform tests. In a videogame, you might test if a player has walked into a wall, or if their health is equal to zero. A machine in a doctor’s office might use Booleans to test if a patient’s heartrate is above or below a certain level.

              Try typing a Number into the Interactions window and hitting Enter. What do you expect to get back? What about a String? Now try a Boolean, such as false. As with all values, Booleans evaluate to themselves. The Circles of Evaluation can also be used with Booleans: try converting each of the following math expressions into Circles of Evaluation, and then converting those Circles into code:

              Give students plenty of practice here! You can see a video demonstration of this intro at Video Lesson: Intro to Booleans

            • There are many other functions that produce Booleans. Here’s one that can be used to compare two Strings:  

              Make sure you’ve written down the complete Contract for all four Boolean functions.

              Make sure students are comfortable using Booleans to compare more complex subexpressions, rather than just comparing two Numbers.

            onscreen? 1.0

            Overview

            Students use the Design Recipe to write a simple, Boolean-producing function

            Learning Objectives

            • Students use Booleans to determine whether a game element is partly visible onscreen

            • Students write functions that use other functions they have written to compute answers

            Evidence Statements

            • Students can write functions that consume a single-axis coordinate and determine whether it is within the boundary of a fixed screen size

            • Students can use one function they have written to compute the answer for another function

            Product Outcomes

              Materials

              • Pens/pencils for the students, fresh whiteboard markers for teachers

              • Student workbook

              • Class poster (List of rules, language table, course calendar)

              • Language Table (see below)

              Preparation

              onscreen? 1.0 (Time 25 minutes)

              • Open the "Cage" program (Cage.rkt from source-files.zip or in WeScheme) on your computer, and click "Run". The window that pops up contains a butterfly, which you can move around using the arrow keys on your keyboard. This butterfly is named Sam, and the window is Sam’s yard. Much like the videogame screen, this yard is 640 pixels wide by 480 pixels tall! As you can see, Sam is free to walk around the yard, and the coordinates at the top of the screen update to tell you his location.

                This may be a good opportunity to review coordinates, for students who need the practice.

              • imageSam’s mother tells him that it’s okay for him to step outside of the yard, but only by a short distance! Specifically, she wants to make sure that she can always see at least a little piece of him. Sam is safe as long as some piece of him is onscreen. That means he can go a little past zero on the lefthand size, or a little past 640 on the right - but how far can he go?

                Turn to Page 19 in your workbook, and read through the top half of the page. Using the arrow keys, see how far Sam can go to the left while still staying onscreen. You’ll find that Sam is onscreen as long as his x-coordinate is greater than -50, which is exactly the code that’s filled in for the first problem on the page.

                • Find out how far Sam can go to the right while still being onscreen.

                • Fill in the code for the second problem.

                • Convert both of those expressions into Circles of Evaluation, using the empty Circles at the bottom of the page.

                Pay close attention to the corner-cases: is Sam on the screen at 690? What about 680?

              • Unfortunately, right now there is nothing to keep Sam from leaving his yard! Looking at the code for this program, we find three function definitions:

                • safe-left?, which takes in Sam’s x-coordinate and checks to see if Sam is safe on the lefthand side of the screen. Right now, this function always returns true.

                • safe-right?, which takes in Sam’s x-coordinate and checks to see if Sam is safe on the righthand side of the screen. Right now, this function always returns true.

                • onscreen?, which takes in Sam’s x-coordinate and checks to see if at least tiny piece of Sam is on the screen. Right now, this function asks safe-left? if the given x-coordinate is safe.

                Right now, all three functions return true no matter what Sam’s x-coordinate is!

                It’s extremely valuable at this point to have three students stand, and act out each of these three functions:

                • Ask each student to tell you their Name, Domain and Range. If they get stuck, remind them that all of this information is written in their Contract!

                • Practice calling each function, by saying their name and then giving them an x-coordinate. For example, "safe-left? fifty" means that the number 50 is being passed into safe-left?. That student should return "true", since the code currently returns true for all values of x.

                • Do this for all three functions, and have the class practice calling them with different values as well.

                • Note: the volunteer for onscreen? should first call safe-left?, before replying with the value.

              • Right now safe-left? is ignoring Sam’s x-coordinate, and blindly returning true no matter where he is. What should the function be doing instead?

                Turn to Page 20 in your workbook. Use the Design Recipe to fix this function, so that safe-left? takes in Sam’s x-coordinate and returns true or false depending on whether it is greater than -50.

                Once you have typed in the EXAMPLEs and definition for safe-left?, click "Run" and see if Sam is prevented from flying off the lefthand side of the screen. Be sure to test your function in the Interactions window as well, for example:  

                Remind students that they’ve already written the check for this on page 19! It may be helpful to have students complete this activity in parts, by giving them a short time to do the Contract and Purpose Statement, then a short time to write their first example, their second, etc. By debriefing and reviewing after each step, you are likely to uncover misunderstandings earlier in the process. Have the three volunteers from earlier stand again, and act out the code now that safe-left? is written properly. As before, make sure students practice calling each function individually: now safe-left? will be able to return true and false (as will onscreen?), while safe-right? still returns only true.

              • Turn to Page 21 in your workbook. Use the Design Recipe to fix this function, so that safe-right? takes in Sam’s x-coordinate and returns true or false depending on whether it is less than 690.

                After walking through safe-right? section by section, students should be able to complete this activity on their own. If students are doing well with programming, you might discuss whether to compare the x-coordinate to 690 or (+ 640 50); both yield the same computation, but the second reveals where 690 comes from (screen width plus 50).

              • Once you have typed in the EXAMPLEs and definition for safe-right?, click "Run" and see if Sam is prevented from flying off the righthand side of the screen. You may be surprised at what happens! Test your function in the Interactions window:   Is safe-right? working the way you expected? Is onscreen? working as you expected? The onscreen? function is only talking to safe-left?, which means that Sam is only protected on the lefthand side of the screen.

                Change the code for onscreen? so that it calls safe-right? instead. Now Sam will be protected on the righthand side of the screen, but not the left. What should onscreen? be doing?

                Have the three actors stand again, and repeat the activity. Now safe-left? and safe-right? behave correctly, but onscreen? is still only talking to safe-left!

              and/or

              Overview

              Students are introduced to and/or, two functions that consume Booleans

              Learning Objectives

              • Students learn to combine Boolean values with and and or

              Evidence Statements

              • Students understand when to use each of and and or

              • Students can write Circles of Evaluation for expressions that use and and or

              • Students can write code expressions that use and and or

              • Students can determine the answers produced by expressions that use and and or

              Product Outcomes

                Materials

                • Pens/pencils for the students, fresh whiteboard markers for teachers

                • Class poster (List of rules, language table, course calendar)

                • Language Table (see below)

                Preparation

                  and/or (Time 10 minutes)

                  • You’ve already learned many functions that allow you to create Booleans. The functions < and >, for example, will each return a boolean when applied to the appropriate input. What happens when you want to combine these tests, to see if more than one thing is true?

                    Consider the following statements - are they true or false?:

                    • Sugar is sweet

                    • Ice is hot

                    • Sugar is sweet and Ice is cold

                    • Sugar is sweet and Ice is hot

                    • Sugar is sweet or Ice is cold

                    • Sugar is sweet or Ice is hot

                    Challenge students on their answers here - ask them to explain why they choose "true" or "false" for the compound statements, especially if the individual statements are a mix of true and false.

                  • and and or are two new functions.  

                    Complete Page 22 in your workbook.

                  onscreen? 2.0

                  Overview

                  Students use the Design Recipe alongside their newfound knowledge of and/or, to write a function that performs two boolean tests.

                  Learning Objectives

                  • Students will be able to compose Boolean functions results using and and or

                  • Students will understand how Booleans and Boolean functions are used to control the behavior of game elements

                  • Students will begin to appreciate why programs are written as compositions of several smaller functions

                  Evidence Statements

                  • Students will be able to write functions that combine screen-boundary tests using and and or

                  • Students will understand why and is necessary to check for two boundaries

                  • Students will be able to explain why re-using existing functions is better than reproducing their computations

                  • Students will understand how they use Booleans and conditional to control how game elements behave at the screen boundaries

                  Product Outcomes

                  • Students detect when game elements have moved offscreen (so they can reappear on the other edge of the screen)

                  Materials

                  • Pens/pencils for the students, fresh whiteboard markers for teachers

                  • Student workbook

                  • Class poster (List of rules, language table, course calendar)

                  • Language Table (see below)

                  Preparation

                    onscreen? 2.0 (Time 25 minutes)

                    • Now that you know how to combine tests, how can onscreen? combine both tests to keep Sam onscreen?

                      Turn to Page 23 in your workbook and write the completed onscreen? function, so that it tests both safe-left? and safe-right?. Type in the examples and definition when you’re done, click "Run", and see if Sam is protected on both sides!

                      Have the volunteers stand once again, and ask the class what onscreen? should do. Should it be using and or or? Be sure to give specific examples of points that are onscreen, too far to the left and too far to the right, and challenge the students to justify their answers.

                    • There are two ways to go about solving the onscreen? word problem:   and...   Does it matter which one you use?

                    • There is more to being a writer than good spelling and grammar. There’s more to being an architect or an artist than building a bridge or coloring in a canvas. All of these disciplines involved an element of design. Likewise, there is more to being a Programmer than just writing code. You’ve gotten decent at writing code, and now you’re able to write sophisticated programs that include multiple functions - congratulations! But that also means you’re ready to consider what it means to design the code that you write.

                    • Suppose you just built a car, but it’s not working right. What would you do? Ideally, you’d like to test each part of the car (the engine, the transmission, etc) one at a time, to see which one was broken. The same is true for code! If you have a bug, it’s much easier to find when every function is simple and easy to test, and the only complex functions are just built out of simpler ones. In this example, you can test your safe-left? and safe-right? functions independently, before stitching them together into onscreen?.

                    • Another reason to define multiple, simple functions is the fact that it lets programmers be lazy. Suppose you have a few characters in a videogame, all of which need to be kept on the screen. Some of them might only need safe-left?, others might only need safe-right?, and only a few might need onscreen?. What happens if the game suddenly needs to run on computers with differently-sized monitors, where the boundary is 1000 instead of 690? If you have simple and complex functions spread throughout your code, you’ll need to change them all. If your complex functions just use the simpler ones, you’d only need to change them in one place!

                    • Badly designed programs can work just fine, but they are hard to read, hard to test, and easy to screw up if things change. As you grow and develop as a programmer, you’ll need to think beyond just "making code work". It’s not good enough if it just works - as artists, we should care about whether or not code is well designed, too. This is what functions allow us to do! Everyone from programmers to mathematicians uses functions to carve up complex problems into simpler pieces, which make it possible to design elegant solutions to difficult problems.

                      Can you list three reasons why it’s good to have several simple functions, rather than a single complex one?

                    • The boundary-detection code you wrote (through safe-left? and safe-right?) is very useful for videogames. It can be used to stop a character from traveling through a wall, or to regenerate the character once it has left the screen.

                      Open your game file, and scroll down past the update- functions until you see the definitions for safe-left?, safe-right? and onscreen?. Right now, they all return true. Since your gamescreen has the same dimensions as Sam’s yard (640x480), you can use the same code for each of these three functions! Make sure you include EXAMPLEs, so that your game code can test each function separately.

                    Closing

                    Overview

                    Learning Objectives

                      Evidence Statements

                        Product Outcomes

                          Materials

                            Preparation

                              Closing (Time 5 minutes)

                              • You’ve learned how to use Booleans to constrain where elements can move in a game. In the next unit, we’ll discuss how to use Booleans to move game elements based on which keys users press while playing your game.