Contact Information Who: Monica Sweat Put “cs1321” in the subject line of any No HTML style ,...

Preview:

DESCRIPTION

Administrivia Homework 1 is due in class. (Now) Homework 2 is on the web now. Recitations are not this week. Recitations begin next week – 2 nd week of class

Citation preview

Contact Information

Who: Monica Sweat sweat@cc.gatech.edu Put “cs1321” in the subject line of any e-mailNo HTML style email, please

What: CS1321, Introduction to Computer Science

When: Lecture -- Tues & Thurs, Noon++ to 1:30 p.m. Recitation -- See OSCAR listing

Where: Office located in Room 121, adjacent the luxurious “bullpen” in the fabulous College of Computing

AdministriviaHomework 1 is due in class. (Now)

Homework 2 is on the web now.http://www.cc.gatech.edu/~sweat

Recitations are not this week.

Recitations begin next week – 2nd week of class

!0. Administrivia

A new version of DrScheme has been placed on the PLT download page.

The version number is 103p1, meaning that it’s just a patch to version 103. Essentially, this means that if you install version 103p1, you do not have to separately download and install the updated “teachpack” files, as described on the cs1321 webpage.

If, however, you downloaded version 103 (no patch), you will have to separately install the updated teachpack files. Again, details appear on the cs1321 homepage.

0. AdministriviaEvidently, version 103 is no longer directly available. You can get it (still) from:

http://www.cs.rice.edu/CS/PLT/packages/download/103/plt

If you wish to reinstall from 103, you can grab a copy from the web page.

SUMMARY:

If you installed version 103 AND the teachpack upgrades, YOU DO NOT NEED TO INSTALL Version 103p1

If you’ve not installed DrScheme, give 103p1 a whirl.

Excellent installation page• Thanks Joe!!

http://www.prism.gatech.edu/~gte067q/initial_setup/drscheme_installation/index.html

(should be all one line, no spaces!!)

Perspective

We might categorize computer languages:

-- BASIC, FORTRAN, C, Pascal

-- Reflect low-level focus of language

-- Programmers must create solutions that reflect the type of hardware, restrictions and limits of the system they are using

procedural or imperative languagesprocedural or imperative languages

Perspective

Object-oriented programmingObject-oriented programming

-- Java, C++, Ada, Smalltalk

-- Programmers must think in terms of data and the behaviors appropriate to that data

-- Less design pressure from the limits and requirements of the computer system.

Perspective

Functional ProgrammingFunctional Programming

-- Lisp, Scheme

-- Programs viewed as a collection of procedures similar to mathematical functions.

-- Much easier to implement

Further Perspective

In addition to labels of functional, procedural, and OO languages, we might also categorize languages based on whether they are interpreted or compiled (or even a hybrid).

Interpreted languages are evaluated one step at a time, with values and variables being determined dynamically at run time.

Compiled languages are assembled into memory, with address locations and offsets precalculated, and then crafted into an “executable” program.

The Big Picture

Compiled

Object Oriented

Imperative/ProceduralFunctional Other

Interpreted

Hybrid

Paradigm

SchemeSchemeLisp

FortranC, Ada

Smalltalk

Java

Basic

C++

Prolog

Review: Scheme Syntax

Given the following choices of notation:

a) infix b) postfix c) PREFIX

Which one does Scheme use?

hint

Functions…

Functions

Let’s start with a simple function from mathematics:

f(x) = x * x

This function squares a number, thus:

f(2) = 2 * 2 = 4

f(5) = 5 * 5 = 25

Functions

Recall that a function:

maps a set of values, called the domain,

onto a set of return values, called the range,

so that one of the domain values is paired with one and only one of the range values.

1

2

3

domain

range

X

f(X) f(X) = X*X

Functional Vocabulary

Consider again:

f(x) = x * x

Parameterto function

Name offunction Function

body

‘binds’ or associatesbody to name and

parameters

Functional Vocabulary

f(x) = x * x

f(2)The function body is “applied to” the value 2

Observations

f(x) = x * x

f(2) = 4

Predictable, reproducible. Each time we apply the function to the value 2, we get the same result.

Nothing changed about the parameter. Each time we call f(2), we do not change the value of 2. “The function doesn’t alter anything in the world.”

Observations

Composable. We can compose a function of other functions.

f(f(2))

The inner f(2) returns 4, so the outer f() call is sent 4.

The overall expression returns 16:

f(f(2)) f(4) 16

Scheme

Elements

Integers, e.g. 4, -6, 0

Real Numbers, e.g., 3.14159

Ratios, e.g., 1/2, 4/3

Symbols, e.g., x, y, weight, height, calcPMT-- often used for the name of a parameter,or a function name, or a variable

Scheme

How would you categorize this:

+Is this a real number? An integer? A ratio?

Perhaps… a symbol?

SchemePredefined symbol.

As it turns out, there are about 100 predefined symbols in scheme, including the arithmetic operators:

+ addition- subtraction* multiplication/ division

Our First Example

Suppose we wished to use the predefined function“sqrt”, which returns the square root of a parameter.

In the interpreter of DrScheme, we’d type:

sqrt(4)

Since we’re used to expressions such as “f(4)” from mathematics.

AhaAs it turns out, in Scheme, you invoke functions like so:

(sqrt 4)

and not:

sqrt(4)

It’s the same amount of typing; the parens are in different locations to clarify. (A more complex example will show the merit of this.)

What if...

When we next type in:

(sqrt (sqrt 4))

we see:

#i1.4142135623730951

That looks like the right value, but what’s with the“#i” in front? This is scheme’s way of indicating an approximation.

So let's write a Scheme function!

Remember square: f(x) = x * xWe start by naming the function

(define (sq x)

and continue by adding the body

(define (sq x)(* x x))

And we test

(sq 3)9

Remember Pythagoras?

And more...

b

a

c

c2 = a2 + b2

c = sqrt(a2 + b2)

And more...

(sqrt (+ (* 3 3) (* 4 4)))5

3

4

c

Note Well

We use prefix notation, instead of infix:

(* 3 3)

Scheme expects the name of the function first. "*" is a function that multiplies numbers together.

Repetition

(sqrt (+ (* 3 3) (* 4 4)))

3

4

c

2

8

c

(sqrt (+ (* 2 2) (* 8 8)))

If we had many triangles to work with, typing the same expression over and over gets tedious.

A Fix

In mathematics, we’d recognize the function at play:

h(a, b) = sqrt ( a*a + b*b )

Remember what that "=" sign meant? It binds the body to the function/parameter list. In Scheme, we can do this binding by ‘defining’ a function. It begins with:

( define

The Fix Is In

At this point, the Scheme interpreter would expect you to name the function you hope to define.

We need to come up with a symbol name.

The symbol “hyp” is good enough:

(define (hyp side1 side2)

Here side1 and side2 are "parameters" or "arguments"

Still More

(define (hyp side1 side2)

At this point, we’ve have a symbol for the name of the function and the names of the parameters to the function.

The body of the function is easy to figure out:

(define (hyp side1 side2)(sqrt (+ (* side1 side1) (* side2 side2))))

Note Well

As a matter of style, we will use indents and returns to better format the statement:

(define (hyp side1 side2)(sqrt (+ (* side1 side1) (* side2 side2))))

As opposed to:

(define (hyp side1 side2) (sqrt (+ (* side1 side1) (* side2 side2))))

(define (hyp side1 side2)(sqrt (+ (sq side1) (sq side2))))

Can we abstract even further?

Note that we need to square the values andwe defined a square function: sq earlier.

(define (hyp side1 side2)(sqrt (+ (* side1 side1) (* side2 side2))))

Numbers and Arithmetic

Outline• Prerequisites

– None

• Objectives– Basic number manipulation

– Simple programs and variables

• Reference – “How to Design Programs”

• 2.1 Numbers & Arithmetic

• 2.2 Variables and Programs

• 2.3 Word Problems

Using Numbers in Scheme• Types of numbers

• Simple arithmetic

• Nesting expressions

• Scheme expressions

• Mathematical operations

• Variables

• Programs

Types of numbers• Positive and negative integers

– Whole numbers– e.g. 123, -45

• Fractions (rational numbers)– e.g. 4/5, 81/100– Not 4/6 -> 2/3

• Real Numbers– Inexact representations– e.g. 3.14159265….

Simple arithmetic• Scheme allows some obvious arithmetic

expressions– Enclosed on parentheses– Terms in a specific order

• (+ 1 3) ->• (- 5 2) ->• (* 12 3) ->• (/ 8 12) ->

• First term is the operation

• The next terms are operands

43362/3

Nesting expressions• Any operand can be replaced by another

evaluated expression

(/ 8 (* 4 (- 5 2)))

• Evaluate the innermost expressions first:

(/ 8 (* 4 (- 5 2) ))= (/ 8 (* 4 3) )= (/ 8 12 )= 2/3

Scheme expressions• Surrounded by parentheses

• First term is the operation

• Subsequent terms are operands

• Specific structure avoids confusion

– Compare (+ 3 (* 4 5))

– With 3 + 4 * 5

Mathematical operations• Numerous built-in functions for common

operations:(sqrt A) -> A(expt A B) -> AB

(remainder A B) -> remainder of integer division A/Be.g. (remainder 23 8) ->

(log A) -> natural log of A(sin A) -> sine of A radians

7

Variables and Constants• Many common formulae use variables

– e.g. area of a circle is r2

• Certain common constants like and e can be given names in Scheme– e.g. (define PI 3.14159265)

• We can substitute any value for the variables in an expression to determine the actual result– e.g. area of a circle of radius 5 is 25 = 78.5

Defining ProgramsTo express a complete program to compute the area of a circle, we use (define … )

(define (area-of-disk r) (* PI (* r r)))– area-of-disk

is the name of the program of function– r

is the input consumed by this particular function– (* PI (* r r))

is the body of the function.

Using ProgramsTo make use of the function we just defined, we treat it like one of the built-in functions:

(area-of-disk 3) = (PI * (* 3 3)) = (3.14159265 * (* 3 3)) = (3.14159265 * 9) = 28.27…

Composing ProgramsWe can now use this new function as a component of other functions:

(define (area-of-ring outer inner) (- (area-of-disk outer) (area-of-disk inner)))

which is a function consuming two inputs to compute the grey area:

outer

inner

Substitution Model of EvaluationTo find a specific disk area, we provide the two radii:

(area-of-ring 5 3) = (- (area-of-disk 5) (area-of-disk 3))) = (- (* PI (* 5 5)) (* PI (* 3 3))) = (- (* PI 25) (* PI 9)) etc.

5

3

Summary

• You should now know…– Basic number manipulation

– Simple programs and variables

– Substitution model of evaluation

– How to implement word problems

Basic Scheme Syntax

Outline• Prerequisites

– Numbers, variables, programs

• Objectives– Basic syntax of Scheme

– Syntax errors

– Logic errors

• Reference – “How to Design Programs”

• Section 2.4

Persistence• Functional programming derives its inherent

purity and power from its absence of persistence

– When we use the area-of-ring function:(define (area-of-ring outer inner) (- (area-of-disk outer) (area-of-disk inner)))it consumes the outer and inner radii, computes the required result and forgets all about the intermediate results

• Persistent expressions result in some permanent change which lasts beyond the lifetime of the function which made the change

Example of Persistence

(define (area-of-ring outer inner) (- (area-of-disk outer) (area-of-disk inner)))

• When the (define … ) function completes, we expect the system to “remember” how to compute the area of a ring so that we can subsequently use that definition.

Distinguish between the act of defining a function and the use of that function definition to compute results

Definitions and Expressions

• Expressions– Collection of symbols intended to compute a value– Used to compose definitions– Evaluated in the Interactions window

• Definitions– Special expressions establishing the rules for

computing a result– Evaluated in the Definitions window using the

Execute button

ExpressionsEither Atomic or Compound• Atomic Expressions

– Numbers, variables, later: symbols

• Compound Expressions– List of entries

• separated by at least one space or line break, and • enclosed in parentheses “( … )”

– First entry is an operation– Zero or more expressions as parameters– e.g (sqrt 49)

(email fred 42)

Definitions• Are really just special compound expressions.• Each “defines” the rules for computing a result for

the function you are writing.– define is the operation you are using– It takes two arguments:

1. A list with new function’s nameand then zero or more formal parameters

2. the function body– One or more expressions specifying how to

compute the result

Definition Example

(define (profit ticket-price) (- (revenue ticket-price) (cost ticket-price)) )

Identifies a definition

Function name Formal

parameter(s)

Body consisting of a subtraction expression

Each parameter is another compound expression consuming the formal

parameter and returning a numerical value

Scheme Errors

• Syntax errors– Comparable to “grammar” errors in natural languages– Scheme verifies that all code is correctly formed according to the

rules

• Run-time errors– Divide by zero for example– Wrong number of parameters when trying to run the function

• Logical errors– The “grammar” is right, but not right solution for your problem.

Like being asked in history class to write an essay about the civil war, and you wrote an excellent essay on Potholes in Atlanta.

Error Examples• (* (7) 2)• (2 * 3)• (/ * 3 4)• (/ 13 0)• (define (fred 1) (+ b 3)))• (define (fred a) + a 3))• (define fred (a) (+ a 3)))

Summary• You should now know…

– Basic syntax of Scheme

– Syntax errors

– Run-time errors

– Logical errors

Designing Programs

Outline• Prerequisites

– Basic Scheme Syntax

• Objectives– Basic recipe for program design

• Purpose

• Examples

• Body

• Tests

• Reference– HTDP Section 2.5 “Designing Programs”

The design recipe:

;;Contract: <name> : <variable type> -> <variable type>

;;Purpose: A brief description of the problem

;;Example: <example of what you would put in> should

;; produce <example of what should happen>

;;Definition

<put your code here>

;;Tests

<put your tests here>

Our revision...;; John Doe;; gt1234a;; cs1321 Homework <number>

;;Contract: <name> : <variable type> -> <variable type>

;;Purpose: A brief description of the problem

;;Example: <example of what you would put in> should

;; produce <example of what should happen>

;;Definition

<put your code here>

;;Tests

<put your tests here>

Let’s work through an example

Write a function area-circle

that calculates the area of a circle.

It will consume a number and return a number.

Contract

;;Contract: area-circle : number -> number

Purpose

;;Purpose: Calculate the area of a circle

Example

;;Example: (area-circle 5) should produce;; 78.5

;;Example: (area-circle 5) |--> 78.5;; (area-circle 1) |--> 3.14

Alternatively:

Definition

;; Definition

(define (area-circle radius) (* 3.14 (* radius radius))

Tests

;; Tests:(area-circle 5);;expected78.5

(area-circle 10);;expected314

“Do I have to do this?”

yes!

“Do I have to do this?”

And it works!

Summary• You should now know…

– Basic recipe for program designsee page 21 or http://www.htdp.org/2001-01-18/Book/node14.htm

• Purpose

• Examples

• Body

• Tests

– Recipes are required. See HW2 for more requirements regarding recipes for this course.

Reading Assignment• We’ve covered pages 1-21 or

to http://www.htdp.org/2001-01-18/Book/node14.htmfromHow to Design Programs!!

• “Programs are Function Plus Variable Definitions” will be next time…