Unit 3:   Introduction to Definitions

imageUnit 3Introduction to Definitions
Unit Overview

Students are introduced to the Definitions window, and learn the syntax for defining values of various types. They are also introduced to the syntax of defining functions and creating examples.

Product Outcomes:
  • Students will name their videogame project

  • Students will modify the definitions for TITLE, TITLE-COLOR, BACKGROUND, PLAYER, TARGET and DANGER

  • Students will define at least two functions, using the Design Recipe

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.

  • 6.NS.5-8: The student performs operations with negative numbers, works with the number line and coordinate plane, order and absolute value of numbers, and solves real-world problems with rational numbers.

    • graphs of negative numbers on the number line.

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

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

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

    • interpretation of expressions that represent a quantity in context

  • F-BF.1-2: The student models a relationship between two quantities by building a function

    • use of recursive and explicit formulas to write arithmetic and geometric sequences to model situations

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

    • explanation that if f is a function and x is an element of its domain, then f(x) denotes the output of f corresponding to the input x

    • evaluation of functions using function notation for inputs in their domains

  • 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

  • BS-DR.1: The student is able to translate a word problem into a Contract and Purpose Statement

    • given a word problem, identify the domain and range of a function

  • 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

    • look to error messages as a way of diagnosing syntax errors

  • 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

  • BS-PL.3: The student is able to use the syntax of the programming language to define values and functions

    • defining and retrieving values

    • writing test cases

    • defining and using functions

Length: 100 minutes
Glossary:
  • contract: a statement of the name, domain, and range of a function

  • define: associate a descriptive name with a value

  • definitions window: the text box at the top of the Editor (DrRacket or WeScheme), where definitions for values and functions are written

  • design recipe: a sequence of steps that help people document, test, and write functions

  • domain: the type of data that a function expects

  • example: shows the use of a function on specific inputs and the computation the function should perform on those inputs

  • function definition: code that names a function, lists its variables, and states the expression to compute when the function is used

  • name: how we refer to a function or value defined in a language (examples: +, *, star, circle)

  • range: the type of data that a function produces

  • value: a specific piece of data, like 5 or "hello"

  • variable name: name of the information that can be different each time a function is used

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

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

  • Language Table (see below)

  • Editing environment (WeScheme or DrRacket with the bootstrap-teachpack installed)

  • "Algebra Translation" [DrRacket | WeScheme] preloaded on students’ machines, with monitors off.

  • Student workbook folders with names on covers.

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 5 minutes)

        • So far, you’ve seen the Circles of Evaluation, learned about Contracts and experimented with multiple datatypes. Make sure you remember what each of those are, and look back at previous lessons for a refresher if you need.

          Can you think of three functions that draw shapes? See if you can write their contracts without needing to look back at your Contracts page. What type of data is always surrounded in quotes? What are the coordinates for the bottom left-hand corner of the screen? What about the top-right?

        Defining Variables

        Overview

        Students define names for simple values (Numbers, Strings and Images) and use them in expressions.

        Learning Objectives

          Evidence Statements

          • Students will be able to define names for Number, String and Image values.

          • Students will be able to identify the name, domain, range, and variable name for a function, when presented with a completed Design Recipe.

          • Students will be able to explain what happens when the "Run" button is pressed.

          Product Outcomes

            Materials

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

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

            • Editing environment (WeScheme or DrRacket with the bootstrap-teachpack installed)

            • Language Table (see below)

            Preparation

              Defining Variables (Time 10 minutes)

              • Suppose we want to make an image that had fifty identical, solid red triangles. You would have to write (triangle 50 "solid" "red") fifty times! To make matters worse, any change to those triangles would have to be repeated for all fifty expressions! Good programmers know that their effort is better spent elsewhere, so they made sure that programming languages have a way to avoid all that repetition. They write something once, define it as a shortcut in the language, and then use the shortcut wherever they want.

              • We name values in our language using define statements. Let’s look at an example of a definition , that defines shape1 to be a solid red triangle. When you click "Run", you can evaluate shape1 in the Interactions window and the computer will show you the triangle. What do you think would happen if you evaluated shape1 without clicking "Run"?

                Make sure students see what happens when shape1 is evaluated without first clicking "Run", so they can read and understand the error. Similarly, have them change the definition and evaluate shape1 again - still without clicking "Run". It’s important for them to understand that running a program causes the computer to read the definitions, and that any change requires it to re-read them.

              • Definitions go in the upper window in your editor (the one above the Interactions Window); this upper window is called the Definitions Window.
                • Enter the shape1 definition into the Definitions Window.

                • Click "Run" to have the computer read that definition.

                • What do you think will happen when you evaluate shape1 in the Interactions window?

                • Add a new line to the definitions window, just below the definition of shape1. Add a new definition called shape2, and define it to be a solid, blue circle of radius 20.

                • Click "Run", and try evaluating shape2.

                • On the next line, define a new value called age to be the number of years old that you are.

                • On the next line, define a new value called name to be the String that represents your name.

              • One a new line in the Definitions Window, define a value called eye-color to be the color of your eyes. Don’t hit "Run" yet!

                • Go into the Interactions Window and try evaluating eye-color. You should get an error message that the computer doesn’t know about eye-color, because you didn’t click "Run" after adding the definition.

                • Click "Run".

                • Try asking for eye-color in the Interactions Window again. This time, you should not get the error.

                Definitions are useful because we can reuse them in other expressions. For example, we could use eye-color inside another expression, such as (circle 10 "solid" eye-color). Let’s practice using definitions inside other expressions.

              • Create the following definitions in the Definitions Window, and check them out in the Interactions Window:

                • Define a value called prize to be a solid yellow star (you pick the size).

                • Define a value called big that uses scale to make your prize three times larger.

                • Define a value called tilt that uses rotate to turn your big yellow star by 45 degrees.

                • Type tilt in the Interactions Window, and make sure you get a large, tilted, yellow star.

                • It turns out that green stars are more popular as prizes than yellow stars. Change the expression in your prize definition to make the star green instead of yellow. Click "Run" so the computer will read your new definition.

                • Now type tilt in the Interactions Window again. What color star did you get? If you defined each of big and tilt to use your definitions, you should get a tilted green star! If you didn’t get a green star, try to fix your definitions to make that happen.

                It is important to give students ample time to experiment with define. Students need to understand that they can use the defined name in place of the value. Have them define several values (each of different types), and then practice using them inside other expressions.

              Defining Variables (Algebra)

              Overview

              Learning Objectives

                Evidence Statements

                  Product Outcomes

                    Materials

                    • "Algebra Translation" [DrRacket | WeScheme] preloaded on students’ machines, with monitors off.

                    Preparation

                      Defining Variables (Algebra) (Time 10 minutes)

                      • In our programming language, variables are defined by: Values can be fixed (like the first example), the result of an expression (the second), or even be defined in terms of other variables (the third). We can do the same things in algebra:

                        Convert the following three Algebra definitions into Racket definitions:

                        For this activity write all Racket expressions on one side of the board, and all algebra expressions on the other. You’ll want to line them up as closely as possible, to reinforce the connection between the two languages.

                      • Turn to Page 38 in your workbooks. You will see a bunch of value definitions written in code - take 2 minutes to convert this into math. GO!

                      Game Images

                      Overview

                      Students define values in their videogames

                      Learning Objectives

                        Evidence Statements

                          Product Outcomes

                          • Students will name their videogame project

                          • Students will modify the definitions for TITLE, TITLE-COLOR, BACKGROUND, PLAYER, TARGET and DANGER

                          Materials

                          • Student workbook folders with names on covers.

                          Preparation

                          • Create student game files. [See the teacher’s guide, located in the protected materials for this course.]

                          • On student machines: Student Game Files (generated from "Game" template [Game.rkt from source-files.zip | WeScheme])

                          Game Images (Time 30 minutes)

                          • Open the videogame file (Game.rkt from source-files.zip or the online template so that you can see the code, and click "Run". (You may need to wait a few seconds for the images to load!) The window that appears is a running videogame, but you probably notice that nothing is moving - even if you hit the "up" or "down" arrows! For now, click the "close" button to return to the code.

                            This file contains a list of definitions, where you will get to define how your game characters look, move, and interact. As you scroll down to the bottom, you’ll see a bunch of dummy definitions that have been filled in for you. It is up to you to come up with definitions for your own game!

                            Scroll to the very bottom of the screen, reading each of the things you will have to define. Stop when you get to the very bottom, where you see (make_game ...) used as part of a definition. What do you notice about the values passed into make_game?

                            make_game is a function that has been provided for you, which takes all of your definitions and assembles them into a running game. Behind the scenes, make_game inserts your definitions inside a giant function that is called every tenth of a second, and uses your definitions to decide what is happening at that moment.

                            You can remind students that Bootstrap:2 will show them how to write this function, and customize it to create more advanced games (multiplayer, maze, etc).

                          • In the Definitions window, you will see that this program defines several values: TITLE, for example, is defined to the be the String "My Game".
                            • If you type TITLE into the Interactions window, what do you think it would evaluate to?

                            • What other definitions do you see?

                            • What are their values?

                            • What are their types?

                            • Try evaluating each of these values in the Interactions window, starting with BACKGROUND

                            The purpose of this activity is to increase students’ confidence in reading and talking about code. Make sure students get a lot of practice speaking aloud, both to each other and to the instructor.

                          • If you don’t like the definitions provided here, you can change them! You can modify the TITLE and TITLE-COLOR to change what is displayed at the top of your screen, and you can change the definitions for your game images as well. (You can upload new image files by clicking the "Images" button in the toolbar, then selecting "upload" from the resulting popup).

                            Images should be in PNG or GIF format. Background images should be 640x480, and character images should generally be no larger than 200px in either dimension. Make sure that the character images have transparent backgrounds! TIP: use animated GIFs for the characters - not only does the animation make the game look a lot better, but these images usually have transparent backgrounds to begin with. For more instructions on setting up the game files and images, read the Teacher’s Guide guide for this course.]

                          • If you want to change one of your definitions so that the image is smaller or larger, you can use the scale function:   This function resizes the Image based on the Number. For example, (scale 10 (triangle 5 "solid" "green")) will make the that tiny triangle ten times as large, while (scale 0.5 (rectangle 200 100 "outline" "purple")) will shrink the rectangle by half.

                            Practice using scale to grow and shrink different images. If you would like to experiment with more functions, try using the contracts below:   Try playing with this example

                            If a student struggles here, you should fall back to the Circles of Evaluation and Contracts. For example: have the student first draw a circle for rotate, and have them use the Contract to figure out what the inputs are. When they get to the second input (the image), ask them what kind of shape they want to rotate. Whatever their answer is, have them look it up in their contracts page, and draw a Circle of Evaluation inside the one they drew for rotate. Once the Circle of Evaluation is correct, have them convert it to code. Once they are confident, you can challenge them to apply another operation to the whole expression, perhaps flipping the rotated shape vertically.

                          • Another definition in this program is SCREENSHOT. This expression uses the put-image function to layer one image on top of another, using coordinates to decide where to place each image.

                            Advertisements for videogames often have static pictures (called screenshots) of the game in action, so people will know what it looks like to play. Change the coordinates used in the definition of SCREENSHOT so that you have a picture of your game. (Remember: the screen is 640 pixels wide, by 480 pixels tall!)

                            This can be a useful opportunity to review coordinates, especially for students who need the practice.

                          • Being able to define values in a programming language is a powerful tool, which allows programmers to simplify their code and make it both more readable and maintainable.

                          Defining Functions

                          Overview

                          Students are get a taste of the Design Recipe, but primarily they’re introduced to the syntax for function definition.

                          Learning Objectives

                          • Students will be able to define very simple functions, given a simple word problem.

                          Evidence Statements

                            Product Outcomes

                            • Students will define at least two functions, using the Design Recipe

                            Materials

                            • Student workbook folders with names on covers.

                            Preparation

                              Defining Functions (Time 20 minutes)

                              • Defining a value is helpful when a program has lots of identical expressions. Sometimes, however, a program has expressions that aren’t identical, but are just very similar. A program that has fifty solid, green triangles can be simplified by defining a single value, as long as they are all the same size. But what if a program has fifty green triangles of different sizes?

                              • Think about the Image functions you have already used, like star and circle. They take inputs and produce images. Similarly, we might want a green-triangle function that takes the size as an input and produces a green triangle. The programming language doesn’t provide this function, but it does let you define your own functions. We want to define our own function (let’s call it gt, for green triangle) that takes in a Number and produces a solid green triangle of whatever size we want.

                                • (gt 10) would be a shortcut for (triangle 10 "solid" "green")

                                • (gt 20) would be a shortcut for (triangle 20 "solid" "green")

                                • (gt 1980) would be a shortcut for (triangle 1980 "solid" "green")

                                • (gt 98) would be a shortcut for (triangle 98 "solid" "green")

                                • and so on...

                                Problems that require a function definition can be phrased as a word problem such as the following:

                                Luckily, we can follow specific steps to define functions from word problems. Let’s work through the steps to define gt.

                                To make this more concrete, have a student "act" as gt. To call the function, another student says "gt ten!" (calling out both the name of the function and the input). The actor responds "triangle ten solid green", to signify the work that the function does when it receives an input.

                              • The first step in defining a function is to write its Contract. Contracts summarize three pieces of essential information about a function:

                                • The Name of the function: in this case, the name is given, as gt

                                • The Domain of a function, which is the types of data that the function expects: in this case, just a single Number.

                                • The Range of this function, which is the type of data that the function produces: in this case an Image since it produces solid, green triangles

                                Here’s the gt Contract written as code. The line starts with a semicolon, followed by the name, a colon, the Domain, an arrow, then the Range:   Word problems give several clues as to the name, Domain, and Range of a function. Be sure to read the problem carefully! Some word problems will describe functions that take multiple inputs in their Domain, or inputs of different types.

                                Open your workbook to Page 9, where it says "fast functions", and write the Contract for the gt function.

                                It is often a good idea to give students examples of different word problems, and have them pick out the contract for each one.

                                Contracts are written as comments in Racket: whenever Racket sees a semicolon, it ignores the rest of the line after the semicolon. This means that you will never get an error message from Racket for a malformed comment. That also means that you have to check your students’ contracts more closely, because the computer will not check anything about them (format or contents).

                              • It’s always a good idea to think through a few examples before defining the function. Examples show the shortcut that a function is trying to provide. This programming language provides a special construct, called EXAMPLE, which helps you write down how the function is used and what it should compute. You can see two such examples here, written under the contract:   These examples tell the computer that writing (gt 50) should produce the same result as (triangle 50 "solid" "green"), and that (gt 100) is equivalent to (triangle 100 "solid" "green"). The word problem specifies that the examples must use the name ’gt’, and must all produce solid, green triangles.

                                In your workbook, write two examples of your own for this function.

                                Be sure to point out that EXAMPLE is capitalized, and that all examples are written in the definitions window. Many students will follow along here without really understanding, simply by pattern-matching. Be sure to ask them lots of questions, to have them justify each step:

                                • Why does the example have to start with gt? (Because it’s the Name of the function, specified in the contract)

                                • How do we know gt requires only one number? (Because it’s the Domain of the function, specified in the contract)

                                • How do we know to use triangle? (Because the word problem tells us what shape it has to produce)

                                • How do we know the triangle has to be solid and green? (Because the word problem tells us what shape it has to produce)

                                • How do we know the correct order for the inputs to triangle? (The contract for triangle tells us)

                                One of the big ideas here is that each step informs the subsequent step. Make sure to explicitly connect them for students, pointing out that the Contract gives strong hints about how to write each part of the examples.

                              • Programmers often write several examples for each function. Examples like these are a way for a programmer to think through their work. Examples also make it easy to look at what parts of the expression can change, or vary, depending on the inputs.

                                Write the following examples on paper and circle the parts of the examples that are different:  

                                Once you know which parts of the expression change, label the circles with a name that describe their contents. For example, in our two gt examples, we have circled the size of the triangle. Your circled and labeled expressions should look like the following diagram:

                                Pay close attention to what students circle: they should circle something in each part of the Example (the function use on the left and the expression on the right); they should also use the same name for the same concept across the expressions. Their circles will correspond to the variables in their functions, so the variables should appear in both the left and the right sides of the Example.

                              • After writing the Contract, two Examples, and the labeled circles, defining the function itself is relatively simple.

                                • Copy everything that stays the same (everything that wasn’t circled) in one of your EXAMPLE lines (onto paper or into your editor)

                                • In place of each circle, write the label you gave to that circle

                                • Change EXAMPLE to define

                                 

                                This can be a good opportunity to point out that the parts of the examples that were changeable (or vary-able) are what determines when we need to use the variable.

                                • On your paper, define the gt function, then type the Contract, Examples and Definition into the Definitions window.

                                • Click "Run", to have the computer read this definition.

                                • Use the function you’ve defined, by typing (gt 100) in the Interactions window.

                                • Try using the function with different Numbers

                              • These steps are knows as the Design Recipe, which is a powerful tool for defining functions based on word problems.

                                In your workbook (still on Page 9), fill out the Contract for this function.

                                • What is the function’s Name?

                                • What is the function’s Domain?

                                • What is the function’s Range?

                                Using the Contract you’ve written, write two Examples for the function.

                                • What part of the Contract helps you fill in the left side of an Example?

                                • What part of the Contract tells you what the function needs as an input?

                                • How can the Range of a function help you write the Example?

                                Looking at those two examples, circle the parts that are change-able, then label them with a good variable name.

                                • Is the variable name you chose the same as the one you chose for gt? Why or why not?

                                • Why is it helpful to choose a variable name before defining the function?

                                Now write the function definition, using the Examples you’ve written.

                                You will want to explicitly connect each step in the Design Recipe to every other step. Ask students to justify each part of their Contract by referring back to the Word Problem, to justify each step of their Examples by referring back to the Word Problem and Contract, and finally to justify each step of the definition by referring to the Examples. The same variable name can be used in multiple functions, just as in math (where many functions use x as the variable name, for example)

                              • Thinking through the word problem step-by-step, we arrive at:  

                              • In your workbook (still on Page 9), fill out the Contract for this function.

                                • What is the function’s Name?

                                • What is the function’s Domain?

                                • What is the function’s Range?

                                Using the Contract you’ve written, write two Examples for the function, then circle and label the variables.

                                • What part of the Contract helps you fill in the left side of an Example?

                                • What part of the Contract tells you what the function needs as input?

                                • How can the Range of a function help you write the Example?

                                • What is a good variable name for what changes between these Examples.

                                Now write the function definition, using the Examples you’ve written.

                                Thinking through the word problem step-by-step, we arrive at:  

                              Defining Functions (Algebra)

                              Overview

                              Learning Objectives

                                Evidence Statements

                                  Product Outcomes

                                    Materials

                                      Preparation

                                        Defining Functions (Algebra) (Time 20 minutes)

                                        • You’ve seen many functions defined in Racket, for example: (define (f x) (+ x 1))
                                          • What is the name of this function?

                                          • How many variables does it take?

                                          • What is the name of the variable(s)?

                                          • What does this function do to the variable x?

                                          • Define a function g, which takes in a variable q and multiplies it by 20.

                                          Make sure students understand that the function is named f, and not "fx" or "f of x". Have students practice other function definitions, to make sure they’re comfortable translating a verbal description into Racket syntax.

                                        • To translate these functions into algebra, we do something similar to what we did with the values. Here is the same function f, written in algebra syntax:

                                          Translate the function g into algebra, using the translation of f as a model. Once that is complete try defining a function , which takes in a variable x and divides it by 2.

                                          Have students practice this translation with a few other functions, again translating from a verbal description (rather than Racket syntax).

                                        • Translate the rest of the functions, listed on Page 38 of your workbook.

                                        Closing

                                        Overview

                                        Learning Objectives

                                          Evidence Statements

                                            Product Outcomes

                                              Materials

                                                Preparation

                                                  Closing (Time 5 minutes)

                                                  • In this unit, you learned how to name values and define functions. You will use named values to provide images for your game elements. You will use functions to make your game elements move. As you will see soon, functions are critical to making games. You’ll do a bit more practice with them in the next unit, including writing your first function that makes something move across the screen.