Sie sind auf Seite 1von 34

Basics of Program Design

Conditions and Structures


Rahul Desai

Booleans
What

are Booleans?
Booleans are variables that can only hold one
of two values
The most common values a Boolean holds
are
True
False

Conditions
What
A

is a condition?

condition is a statement that is executed if


Booleans associated with the statement
evaluate to either true or false

Types of Conditions
In

programming, conditions are of a


mathematical variety
There are 5 types of mathematical conditions
used
They are

< - Less Than


> - Greater Than
= - Equal To
<= Less Than OR Equal To
>= Greater Than OR Equal To

Evaluate

the following conditions

(and (> 4 3) (<= 10 100))


True
(or (> 4 3) (= 10 100))
True
(not(=23))
True

Evaluate

the following conditions for x =

4
2
7/2
(> x 3)
For x = 4, True
For x = 2, False
For x = 7/2, True

(and (> 4 x) (> x 3))


For x = 4, False
For x = 2, False
For x = 7/2, True

(= (* x x) x)
For x = 4, False
For x = 2, False
For x = 7/2, False

Translate

the following five intervals on the real line into


Racket functions that accept a number and return true if
the number is in the interval and false if it is outside:
An interval boundary marked with ( or ) is excluded
from the interval; an interval boundary marked with [
or ] is included.

the interval (3,7]:


the interval [3,7]:
the interval [3,9):
the union of (1,3) and (9,11):
and the range of numbers outside of [1,3].

Conditionals
What

is a conditional expression or conditional?

A conditional is an expression that determines which condition out of several is true for
any given input
The general shape of a conditional expression is
(cond
[condition return-value]
...
[condition return-value])
OR
(cond
[condition return-value]
...
[else return-value])

Designing a Conditional
Inspect

the problem statement for distinct situations and


enumerate all possible situations
Choose at least one example per situation, for intervals or
enumerations, the examples must include borderline cases
Write down the skeleton of a cond expression, with one
clause per situation. Formulate one condition per situation,
using the parameters. Ensure that the conditions
distinguish the examples appropriately
Deal with each cond-line separately. Assume the condition
holds and develop a Racket expression that computes the
appropriate answer for this case

Suppose

the bank pays 4% for deposits of up


to $1,000 (inclusive), 4.5% for deposits of up
to $5,000 (inclusive), and 5% for deposits of
more than $5,000. Create a Racket function
that takes in the deposit amount and returns
the interest rate for the given deposit

The

3 conditions are

If the deposit is up to $1000, the interest rate is


4%
If the deposit is up to $5000, the interest rate is
4.5%
If the deposit is more than $5000, the interest rate
is 5%

Example:
For $900, the interest rate is 4
For $4500, the interest rate is 4.5
For $6000, the interest rate is 5
Expression:
(cond
[(<= deposit 1000) 4]
[(<= deposit 5000) 4.5]
[else 5])

Conditional Functions
Develop

a function for the previous


conditional
(define (interest-rate deposit)
(cond
[(<= deposit 1000) 4]
[(<= deposit 5000) 4.5]
[else 5])
)

Homework
An equation is a claim about numbers; a quadratic equation is a special kind of equation. All quadratic equations (in one
variable) have the following general shape:
a*x^2 + b*x + c = 0
In a specific equation, a, b and c are replaced by numbers, as in 2*x^2 + 4*x + c = 0
The variable x represents the unknown.
Depending on the value of x, the two sides of the equation evaluate to the same value. If the two sides are equal, the
claim is true; otherwise it is false. A number that makes the claim true is a solution. The first equation has one solution, 1, as we can easily check:
2*(-1^2) + 4*(-1) + (-1) = 0
The number of solutions for a quadratic equation depends on the values of a, b, and c. If the coefficient a is 0, we say the
equation is degenerate and do not consider how many solutions it has. Assuming a is not 0, the equation has
- two solutions if b^2 > 4*a*c
- one solution if b^2 = 4*a*c
- no solution if b^2 < 4*a*c.
To distinguish this case from the degenerate one, we sometimes use the phrase proper quadratic equation.
Develop the function how-many, which consumes the coefficients a, b, and c of a proper quadratic equation and
determines how many solutions the equation has:
(how-many 1 0 -1) = 2
(how-many 2 4 2) = 1
Make up additional examples. First determine the number of solutions by hand, then with DrRacket.
How would the function change if we didn't assume the equation was proper?
Hint: The discriminant of a quadratic equation is b^2 - 4*a*c

Symbols
Symbolic

data consists of the following:

Strings
Symbols (character map)
Characters
Images

Symbolic

data consists of a keyboard character/ series of


characters preceded by a single quote

Symbols

were first introduced to computing by researchers in


artificial intelligence who wanted to design functions that
could have conversations with people

Racket

provides only one basic operation on


symbols: symbol=?, a comparison operation.
It consumes two symbols and produces true if
and only if the two symbols are identical
(symbol=? 'Hello 'Hello) = true
(symbol=? 'Hello 'Howdy) = false

Since

the symbol comparison operator


returns true or false, i.e., Boolean values, it
can be used in a conditional structure

(define (reply s)
(cond
[(symbol=? s 'GoodMorning) 'Hi]
[(symbol=? s 'HowAreYou?) 'Fine]
[(symbol=? s 'GoodAfternoon) 'INeedANap]
[(symbol=? s 'GoodEvening) 'BoyAmITired]))

Develop

the function check-guess. It consumes two numbers, guess and


target. Depending on how guess relates to target, the function produces one
of the following three answers: 'TooSmall, 'Perfect, or 'TooLarge.
The function implements one part of a two-player number guessing game.
One player picks a random number between 0 and 99999. The other
player's goal is to determine this number, called target, with the least
number of guesses. To each guess, the first player responds with one of the
three responses that check-guess implements.
The function check-guess and the teachpack guess.ss implement the first
player. The teachpack picks the random number, pops up a window in which
the second player can choose digits, and hands over the guess and the
target to check-guess.
To play the game, set the teachpack to guess.rtk using the Language|Set
teachpack option. Then evaluate the expression (guess-with-gui checkguess) after check-guess has been thoroughly tested.

Homework
Develop the function check-color. It implements a key portion of a color guessing game. One player picks
two colors for two squares; we call those targets. The other one tries to guess which color is assigned to
which square; they are guesses. The first player's response to a guess is to check the colors and to produce
one of the following answers:
'Perfect, if the first target is equal to the first guess and the second target is equal to the second guess;
'OneColorAtCorrectPosition, if the first guess is equal to the first target or the second guess is equal to the
second target;
'OneColorOccurs, if either guess is one of the two targets; and
'NothingCorrect, otherwise.
These four answers are the only answers that the first player gives. The second player is to guess the two
chosen target colors with as few guesses as possible.
The function check-color simulates the first player's checking action. It consumes four colors; for simplicity,
we assume that a color is a symbol, say, 'red. The first two arguments to check-color are "targets", the
latter two are "guesses". The function produces one of the four answers.
When the function is tested, use the teachpack to master.rtk to play the color-guessing game. The
teachpack provides the function master. Evaluate (master check-color) and choose colors with the mouse.

Structures
What

is a structure?
A structure is a collection of related data
For example, an audio track has several
pieces of related data

The
The
The
The

artist name
album name
year of release
genre

mathematical vector also consists of 2


pieces of related data
The direction it is in
Its magnitude

So

how do we formally define a structure?


A structure is compound data that
combines a number of values into a single
piece of data

Structures in Racket
Pixels

A pixel has an x and y coordinate which represents


its position on the screen
A pixel in Racket is represented with a posn
structure
The posn structure combines 2 numbers, an x
and a y coordinate respectively
How

do you create a posn structure?

Every

structure in Racket, has a make


operation that creates the structure. This
operation is called a constructor.
For example
(make-posn 3 4)
(make-posn 4 6)
(make-posn 8 2)

Let

us define a distance to 0 function that measures the


distance between a pixel and the origin on the screen. The
formula to find the distance between a point and the
origin is (x^2 + y^2)

(distance-to-0
5
(distance-to-0
5
(distance-to-0
10
(distance-to-0
13

(make-posn 0 5))
(make-posn 3 4))
(make-posn 8 6))
(make-posn 5 12))

The

above function takes a pixel and returns the


distance of the pixel from the origin on the screen
So how does one define this function?
You need 2 values to define this function
The x coordinate
The y coordinate
But

the input is a pixel


So how does one extract the x and y coordinates
from the pixel?

Racket

provides the ability to extract


information piece by piece from a structure
by the providing a function for the same
called a selector. Selectors have the syntax
structure name-structure value
In case of the posn structure, there are 2 functions
to extract the x and y coordinates

(posn-x (make-posn 7 0))


7
(posn-y (make-posn 8 9))
9

Lets

put all this information together

A pixel can be represented with the make-posn


function
(make-posn 5 6)

A pixels x coordinate can be extracted using the xposn function


(posn-x (make-posn 5 6)) = 5

A pixels y coordinate can be extracted using the yposn function


(posn-y (make-posn 5 6)) = 6

Let

us create the function


(define (distance-to-0 pixel)
(sqrt
(+
(sqr (posn-x pixel))
(sqr (posn-y pixel))
)
)
)

Creating Custom Structures


Custom

structures can be created using the definestruct function


Example: (define-struct moviestar (last first bestmovie
sales))
The above example, when executed, automatically
creates the following constructor and selectors:

make-moviestar
moviestar-last
moviestar-first
moviestar-bestmovie
moviestar-sales

(define-struct

movie (title producer))

(define-struct

friend (name hair eyes phone))

(define-struct

student (name roll-number))

(define-struct

CD (artist title price))

(define-struct

sweater (material size producer))

Creating Simple Shapes in Racket


For

the following functions, use the teachpack draw.rtk

1. 'draw-solid-line', which consumes two posn structures, the beginning and


the end of the line on the canvas, and a colour.
2. 'draw-solid-rect', which consumes four arguments: a posn structure for
the upper-left corner of the rectangle, a number for the width of the
rectangle, another number for its height, and a colour.
3. 'draw-solid-disk', which consumes three arguments: a posn structure for
the center of the disk, a number for the radius of the disk, and a colour.
4. 'draw-circle', which consumes three arguments: a posn structure for the
center of the circle, a number for the radius, and a colour.

Evaluate

the following expressions in order:

1. (start 300 300), which opens a canvas;


2. (draw-solid-line (make-posn 10 10) (make-posn 110 10) 'red), which draws a red line
close to, and parallel to, the upper end of the canvas;
3. (draw-solid-rect (make-posn 10 30) 100 50 'blue), which draws a blue rectangle of
width 100 and height 50 parallel to the red line;
4. (draw-circle (make-posn 110 30) 30 'yellow), which draws a yellow circle of radius 30
centered at the upper right corner of the rectangle;
5. (draw-solid-disk (make-posn 10 80) 50 'green), which draws a green disk of radius
50 centered at the lower left corner of the rectangle; and
6. (stop), which closes the canvas.

Homework
Define

a structure student that has the following


properties:
the first name
the last name
the name of the teacher

Design

a function check, which is supposed to


return the last name of the student if the
teacher's name is equal to the students
teachers name and 'none otherwise

Homework
Provide

a structure definition and a data


definition for representing colored circles. A
circle is characterized by three pieces of
information: its center, its radius, and the
color of its perimeter. The first is a posn
structure, the second a number, and the third
a (color) symbol.

Das könnte Ihnen auch gefallen