Sie sind auf Seite 1von 9

CS17 Integrated Introduction to Computer Science Hughes

Lecture 02: Functions and Racket


10:00 AM, Sep 9, 2016

Contents

1 Announcements 1

2 Functions 2

3 Sets and Set Notation 4


3.1 Set Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.2 Ordered Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.3 More on Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.4 Cartesian Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

4 Models and Baggage Handling 6


4.1 A Model for Processing Racket Programs . . . . . . . . . . . . . . . . . . . . . . . . 6

5 A bit more Racket 7

6 Summary 8

Objectives

By the end of this lecture, you will be able to:

identify and describe functions

understand set notation and equality

understand how a program is processed using a REPL model

1 Announcements

Women in Computer Science (WiCS) is working to increase the number of women in the
Computer Science field. They offer mentoring and outreach programs, as well as host social
events for women in the CS department to get to better know each other. Click here for their
website or here for their Facebook page. WiCS is open to anyone whos interested in joining.

Contrary to what was said in class, beginning on Monday, we will meet in Metcalf Auditorium
beginning Monday, 9/12.
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

Register ASAP, so that we can get you into a lab section for Sunday and create an account on
the CS department machines. This is very important, since it is the only way that you can
get graded. The deadline to fill out the Lab Preference Form is Saturday at noon. Failing to
do so will result in you not being assigned a lab time this week, and consequently a grade of 0
on your first lab assignment.

If you have not received an email regarding lab signups and homework release, contact the
HTAs. Their email address is: cs017headtas@cs.brown.edu

Your work for this class will be graded primarily by the TAs. Spike will join them sometimes,
especially early in the grading of a project. But theyll do this grading by following a carefully
written rubric, developed by previous professors for this course, and by me as well.

Laptops and phones are not allowed in class.

3-2-1 quizzes: Sometimes Spike will ask a question in class and ask everyone to answer it
out loud after my 3-2-1 countdown. This will be a way for Spike to assess both his teaching
and your understanding.

Homework 1 will be out by later today. Due Tuesday.

Shriram Krishnamurthi, the professor of CS19, gave a brief overview of that class. Over
the next few weeks, 4 supplemental assignments will be released. Students who complete
the assigments well and perform well in CS17 will be offered an invitation to CS19. No
background experience is required, and feel free to contact the CS19 TAs for assistance with
the supplemental assignments.

2 Functions

Our first language is Racket, and its called a functional programming language. This use of the
word functional is not the commonplace one where it means not broken, as in Is your car
functional, or is the battery still dead? Instead, it means based on the mathematical idea of
functions. So lets talk about those for a few minutes.
Youve all probably encountered functions in your algebra class, something like

f (x) = x + 3.

Everyone agrees that this denotes a function called f that adds 3 to a number. But any working
mathematician, on being shown this, will probably not say that it describes a function at all. The
mathematician will insist that you specify a bit more: exactly what can x be? And what kinds of
results can be produced? So a mathematician, describing that same function, will write this:

f : N N : x 7 x + 3.

Here N is a standard symbol from math and denotes the set of natural numbers, {0, 1, 2, . . .}, and
we can read this, from left to right, as saying f is a function that takes in natural numbers and
produces natural numbers; for a typical natural number x, the value produced by f is x + 3.
The first N is called the domain, the second is called the codomain, and the thing with the 7 arrow
is called the rule.

2
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

This might all seem pretty pedantic after all, were just adding 3 to a number! but I want
briefly to come out in favor of pedantry in this situation. Being really precise about what something
means is at the very center of what well do in CS17, and since functions are one of the main objects
of study in computer science, getting this right really matters. So almost every time I discuss
a (mathematical) function, Ill use the notation above: Ill indicate the name, the domain, the
codomain, and the rule. The arrow between domain and codomain will be an ordinary one; the one
indicating the rule will be a 7 arrow.
Now, in algebra class, you spent a lot of time talking about variables, which were typically place-
holders for numbers. You suffered through problems like x is a number less than ten with the
property that x, multiplied by 20 x, is 75. Whats x? (Answer: 5. But that doesnt matter.) In
CS17, were going to talk a lot about functions, and sometimes well have an unknown function f
and want to say something useful about it without saying precisely what it is. So well need ways to
talk about a whole function, rather than just f (4) or f (9) or some other value. With numbers, we
can say things like x < 5 or even x < y, where y is some other as-yet-unknown number. When we
do so, it tells us something about the unknown number x. (In the example above, if I hadnt said
that x < 10, then the solution could have been x = 15 instead of x = 5, for instance).
Well be doing similar things for functions. But to do so, we need a notion of when one function is
less than another, one that well begin to develop (very slightly) in the first homework.
Before that, however, I want to tell you what a mathematician means by saying that two functions
are equal . To be equal functions, f and g must

have the same domain

have the same codomain, and

have the same rule, i.e., for every x in the domain, we must have f (x) = g(x).

That means that the function that takes a real number and squares it is not the same as the function
that takes an integer and squares it, even though both might have been written, in your algebra
book, as
f (x) = x2 .

This might seem crazy to you. Youre thinking Youve got the formula x2 isnt that enough?
And the answer is No, not really. Lots of stuff in math seem crazy at first, like the rule that
the product of two negative numbers is positive, but after a while, it not only seems natural, but
begins to seem like the only way things could be. I want to be clear here, though: the choice of
defining a function in mathematics as having a domain, codomain, and rule, is a purely human one.
Mathematicians tried other definitions, and found that it was harder to write clear and unambiguous
proofs with those, and eventually, after a few hundred years, settled on this meaning and notation.
Its one that works really well, and it turns out to be one thats far better adapted to most of
computer science than the functions are just formulas version. So its the one well be using.
Not every function well want to look at has a rule that can be written using simple algebraic
notation. Well see an example or two next time.
We can even have functions that are described entirely in words, like the function that assigns to
each U.S. president from 1960 to 2011 that presidents party affiliation. It turns out that this last
category of functions really dominates: many of the programs you write will be ones that compute

3
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

functions that are best expresssed in ordinary words. But the ordinary words used to express them
have to be written very carefully to make the function description unambiguous.

Question: Write out a function that rounds real numbers up to the next integer.
Answer: Since the outputs are not just numbers, but are integers, Im going to declare the
codomain to be integers, but an equally good function would be one where we chose the codomain
to be the real numbers. Anyhow, heres my description of that function:

f : R Z : x 7 the smallest integer greater than or equal to x. (1)

3 Sets and Set Notation

A set is a collection of things. Thats a pretty informal description, but it turns out that trying to
formalize the notion of a set is essentially hopeless. So well just use this intuitive description, and
Ill mention along the way some of the ways we can work with sets.
Some folks may have already seen the notion of sets (which scares me, because you might have been
told wrong things), and others may not. Not a problem. Im going to start out by talking about
two ways to describe sets, because it is important for the rest of this class.
Small sets are typically defined by just listing all their elements, between curly braces. As an
example, {3, 2} is a set.
The most important thing about a set is that we can say whether something is in it or not. I
mentioned the set of natural numbers a few minutes ago, and indicated its contents by saying 0, 1,
2, and so on. Having heard that, you can say OK, so the number 2 is in N. And you can also
say (assuming you recognize the and so on in the same way that I do!) that negative three is
not in the set N. Nor is 3.5, or the word cheese. The symbol that indicates that something is in
a set is , so we say 2 N, which is read aloud as 2 is in N, or 2 is an element of N. To say
something is not in a set, we use ,
/ as in 3.5
/ N.
In this form of set-description, the things between the braces are the only elements of the set. So if
I define a set A = {1, 6} and say that x is in set A, you can confidently say that x is either 1 or 6.
If I say that 3 is an element of A, you can confidently say that it actually is not. These things are
unambiguously true or false.
In describing a set using braces, the order is irrelevant, and duplication is irrelevant. As a matter of
habit, we usually omit duplicates and write sets of numbers in ascending order and sets of words in
alphabetical order, but thats merely habit, and not necessary.

3.1 Set Equality

Now that we know at least one way to form sets, we can explore the notion of set equality.
For two sets to be equal, they need to have the same elements. Order does not matter. Nor does
the number of times the same element appears in a set. In other words, for two sets to be equal, all

4
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

elements of one set must be in the other set and vice versa.
Some might think that the shorter notation (in which we never list an element twice) means sets
dont contain things twice, but really all the set-construction notation tells you is which statements
about element of are true.
For example, the sets {6, 1, 1, 1} and {1, 6} are equal because they both contain 6 and 1; it does not
matter that the order is different and that the first set-description contains 1 multiple times.

Question: Is there any value in that redundancy?


Answer: None at all that I can see offhand. But its allowed, so I thought Id mention it.

3.2 Ordered Pairs

In your algebra classes, you probably used the cartesian plane and coordinates to graph things,
and for those coordinates you used ordered pairs of the form (x, y) where x told you where you
were on the x-axis and y told you where you were on the y-axis. And the important thing about
coordinate pairs was that you knew which coordinate was which. The notation (a, b) denotes a
collection in which the first item is a and the second item is b, always in this order. The order
matters, so (a, b) = (c, d) if and only if a = c and b = d.
The ordered pair is very different from a set because in a set, order does not matter. For example,
the sets {1, 6} and {6, 1} are equal (because they have the same elements: remember the definition
of set equality!) while the ordered pairs (1, 6) and (6, 1) are not.
Ordered pairs can be (quite cleverly) described in terms of sets, but thats really a topic for a logic
course, so I wont cover it. If youre intrigued, visit me during office hours.
Similarly, an ordered triple is a list of 3 elements in a certain order.

3.3 More on Notation

For small sets, listing elements works as a way to construct or describe the set. But for other sets,
listing elements is not so practical. One useful form allowed by set theory is this:

Q = {x A | x < 5}.

This notation means that the set Q consists of all elements in the set A that are less than 5. The
vertical bar can be read as with the property or such that. Note that some people also use :
instead of | - I use both, so do not be surprised if you see both.

3.4 Cartesian Product

The Cartesian product of two sets is the collection of all ordered pairs in which the first element
comes from the first set, and the second element comes from the second set. This idea can best be
demonstrated by a simple example. Consider the following two sets containing only two elements
each:
A = {1, 2} B = {3, 4}

5
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

The cartesian product of these two sets, denoted by A B, is the collection of all ordered pairs
such that the first element in the pair comes from set A, and the second element in the pair comes
from set B:
A B = {(1, 3), (1, 4), (2, 3), (2, 4)}

4 Models and Baggage Handling

Supposed you build a model airplane. It might not fly like a real airplane does; you might need to
hold it up with your hand. But, it looks like an airplane. So, you can say that visually, its a model
of an airplane (though mechanically, not so much). A model captures most aspects of something,
but not everything rather it captures what is salient to you.
Suppose you take an airplane flight from Providence to Chicago. When you arrive in Chicago, your
luggage will be available for pickup at a carousel in the airport. How did your luggage get there?
You probably think that you drop your luggage off on the conveyor belt in Providence, it disappears,
some luggage handler loads it onto the plane to Chicago, the luggage handler in Chicago unloads it
when the plane arrives, and then it appears on the carousel.
Now, imagine that your younger brother has been home sick with the flu, and has a terrible fever.
He watches something on the history channel about airplanes, and then watches a rerun of the
Wizard of Oz. He somehow conflates these ideas in his head and gets a rather different idea of how
luggage is handled. Perhaps your brothers model becomes that the luggage goes to the back of the
airport in Providence, and then flying monkeys come and pick it up, transport it to Chicago and
deposit it there, where it comes out on the carousel. Your brothers model is ludicrous; you know
this. But from a practical point of view, it predicts exactly what you need, namely Oh, when I get
to Chicago my luggage will be waiting at the carousel.
There is a place at which this model breaks down completely: if your luggage does not arrive at the
carousel, you will probably want to talk to a luggage handler, while your brother will say no, just
talk to the flying monkeys! And at that point, the failure of the model becomes critical. However,
for ordinary operations, the flying monkey model and the luggage handler model are functionally
the same.

4.1 A Model for Processing Racket Programs

In this course, we will be learning a programming language called Racket, and I am going to give
you an operational description of how this language works. Roughly speaking, I am going to be
telling you about flying monkeys. I am going to give you a description of how the Racket language
might be processed to get the results that you see. What I tell you is not necessarily going to be
the truth. However, this description will be accurate enough that you will be able to predict the
behavior of any program you write.
The Racket programs youll write will be written in an integrated development environment (IDE)
known as DrRacket. DrRacket will take in your code 1 , do something to it, and then return some
results. What DrRacket does may or may not be exactly what I describe. But that doesnt matter.
All that matters is that the behavior is predictably the same in both cases.
1
Computer programs are sometimes called code.

6
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

The reason I describe DrRacket this way is that your third project is going to be a program whose
input is a Rackette program Rackette is a tiny subset of Racket and whose output is going to
be whatever the input program produces. So you will write something like DrRacket. To do so, you
need to have some pretty good sense of how things could work, so you can mimic that.
The story Im going to tell you is exactly the one youre going to use for implementing Rackette.

5 A bit more Racket

...
( let
( [ alon1 ( l i s t 1 2) ]
[ alon2 (map ( lamda ( x ) ( / x 4 . 0 ) ) ( l i s t 2 1 4 ) ) ] )
(map + a l o n 1 a l o n 2 ) )
...

Above is a Racket program. You should be looking at this and thinking I have no idea what it
means. But lets just look at it visually. The ... means that I am showing you a part of a larger
program. There are some parantheses and braces, there are some lists of characters, there are some
things that look like numbers, there is a slash...
I said no magic, but this is the first place where I wont rely on magic, but on something that
you probably believe: its possible to write a computer program that looks at text and separates it
into parts in some way. Im suggesting this based on your experience. Youve probably used Find
in your favorite word processor and it manages to find a particular piece of text. This finding
process is a lot like being able to find parentheses, or numbers, or slashes, etc. Anyhow, believing
that its possible to break program text into those fundamental pieces is the first thing Im hoping
youll believe without proof, for at least a couple of weeks.
While Im getting you to commit to things, I am also going to get you to commit to the idea that
somehow, inside the box, a computer can do arithmetic.
OK, with those two commitments, let me tell you a little more about how Racket programs get
processed.
As I said already, the first step in processing Racket programs that we will be writing is going to be
that we look at them and break them into parts:
Whitespace: blanks, tabs, line breaks, etc

Punctuation: for now, only parentheses and square braces

Other stuff: More on this as we go along.

And Im going to assume that that process of taking program text and turning it into separate
bits is doable. I am going to build up from those recognizable bits to whole programs. And to say
whats a legal program, I am going to describe the shape of program pieces.
We are going to start with a very limited version of Racket. The entities that we are going to be
working with are numbers. Of course, they will be more entities later, but for now numbers are

7
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

going to be the only allowable entities. Numbers are things that look like a bunch of digits, maybe
a decimal point, maybe a + or a - sign in front.
In our model, the processing of a Racket program can be broken down as a formulaic set of three
main steps:

Reading. The first step in processing a program involves reading the program text. Doing so
involves something known as tokenizing: breaking the code down into individual components
such as parentheses, words, etc. Next, parsing involves recognizing program entities and
somehow representing them in the computer; luckily, this is DrRackets job and not yours.

Evaluating. Although this step should really be processing-or-evaluating, it has historically


been referred to as simply evaluating. This step involves taking the entities resulting from
the reading step and producing something new. As an example of non-racket evaluation, in
arithmetic we say that 17 + 18 evaluates to 35.

Printing. The last step involves displaying the resulting value, if appropriate. The printed
representation of things is usually very similar to what is originally typed into the program.

This structured Read-Evaluate-Print set of steps can occur numerous times throughout the process of
evaluating a program. Due to its cyclical nature, this set of steps is referred to as a Read-Eval-Print
Loop, or a REPL for short.
Im being a little sloppy here: Ive used the words program, text, entity, value, and probably some
others here without clear definitions. Ill come back to each of these.

6 Summary

Skills

For two functions to be equal, they must have the same domain, the same codomain, and the
same rule.

For two ordered pairs (a, b) and (c, d) to be equal, a must equal c, and b must equal d.

Sets are a collection of things. We will call these things elements. We use the symbol to
represent that an element is in a set. Order in a set does not matter; duplicates in a set do
not matter.

Ideas

Functions have a domain, codomain, and rule.

The Cartesian product of two sets is the collection of all ordered pairs in which the first
element comes from the first set, and the second element comes from the second set.

The processing of Racket programs can be broken down into three steps. Well call this
structure Real-Evaluate-Print-Loop, or REPL, due to its cyclical nature.

8
CS17 Lecture 10:00
02: Functions
AM, Sep and9,Racket
2016

Reading - we break the program text down into tokens through a process calld tokenizing.
Then, DrRacket parses the programs.
Evaluating - We take what weve found from the reading step, and produce something
new. For example, well evaluate 17 + 18 to be 35.
Printing - we will display the resulting value, when appropriate.

Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any
other CS17document by filling out the anonymous feedback form: http://cs.brown.edu/courses/
cs017/feedback.

Das könnte Ihnen auch gefallen