Welcome to the Week 8 summary of my Haskell class for kids.  If you’re just joining us, feel free to browse through weeks 1, 2, 3, 4, 5, 6, and 7.

# A Brief Review

Just to set the stage: we spent quite a few weeks on pictures, and just last week we started on animations.  We learned:

• Whereas pictures were just variables, animations are functions.
• They have a single parameter, which is how many seconds since the program started running.
• The result of the function should be a picture.

To define a function, we give the parameter a name on the left side of the equal sign, right after the function name.  We can then use that name after the equal sign, just like if it were a number.  Here’s an example:

`animation t = rotate (60*t) (rectangleSolid 40 200)`

The function is called animation.  The parameter is called t.  And after the equal sign, we can use t just like any other number.  For example, we can multiply it by 60, and then rotate the picture by that many degrees.

The result of functions comes from substitution.  So to find out what this animation will look like after 5 seconds, the computer just looks at everything after the equal sign, and replaces any t that it sees with a 5.  So it takes the following steps:

1. animation 5 — this is what the computer starts out trying to figure out.
2. rotate (60*5) (rectangleSolid 40 200) — It replaces any t by 5 after the equal sign.
3. rotate 300 (rectangleSolid 40 200) — This is just math: the computer calculated 60 times 5, and got 300.

So after 5 seconds, the computer will draw the rectangle rotated by 300 degrees.  If you try this out with a few numbers, you’ll notice that the rectangle turns by more and more degrees over time, making it spin.

### So What’s the Problem?

We played around with animations that change lots of things: by t in different places, you can make things spin (using rotate), move (using translate), or get bigger or smaller (using scale, or by using t as the parameter to Gloss functions like circle).  But you might have noticed something disappointing about doing anything except rotation: after a while, the numbers get too big to see!  Things move off the edge of the screen, or get so big you can’t see them any more.

Because of this, our programs so far haven’t really done anything except rotate.  To do much more without everything ending up too big or too far off the screen, we’re going to have to get comfortable with a different kind of function…

# Functions That Give Back Numbers

Animations are functions that get a number, and turn it into a picture.  But that’s not the only kind of function!  We’ve actually seen quite a few kinds of functions, if you count the ones that Gloss defines for us:

• circle is a function that turns a number into a picture (just like animations, but the number means something different)
• light is a function that turns a color into a different color.
• rotate is a function that turns a number and a picture into different picture (one that’s rotated).
• polygon is a function that turns a list of points into a picture.

In general, you can think of a function as a machine that turns things into other things:

You feed the parameters in, and you get the result out the other side.  Different functions need different types and different numbers of parameters, and they give you different types of results, too.  So when you want to use a function, the first things you should ask are: (1) How many parameters does it need? (2) What types of things does it want for its parameters?  And, (3) What type of thing is it going to give me back when it’s done?

In the end, you want to create pictures, of course!  So at first you might think that you’re only interested in functions that give you pictures back.  But that would be short-sighted!  Remember the functions light and dark?  They are functions that expect one parameter – a color – and give you back another color, not a picture.  But they’ve still been very useful for building your pictures, haven’t they?

The same thing is true with numbers.  Even though you ultimately want to end up with a picture, it’s very useful to be familiar with some functions that work with numbers, because we use numbers all the time when we’re making pictures.  So we’ll spend a lot of this week talking about functions that work with numbers.

## How to Draw a Function on Numbers

When you have a function that expects a number for its only parameter, and gives you back a number as a result, we have a convenient way to draw it.  It might look weird at first, but believe me, it makes things a lot easier!  So here’s how to draw a function.  It only works if the function is from numbers to other numbers.

We start out by drawing two lines: one horizontal, and one vertical, like this:

I’ve called the vertical line f and the horizontal line t.  That’s because normally, the horizontal line will represent the amount of time the program has been running, and we’ve been calling that t.  The f is just short for “function”.

Next, you want to label the tick marks on the lines: for t, just number them 1, 2, 3, 4, and so on.  Zero is where the two lines cross, so the first tick mark after that should be 1.  For the vertical line, how you label it depends on the numbers you’re working with!  Notice it’s got both positive and negative numbers, too.

The next step is to draw some points.  Ask yourself, if you give your function is given the number 0, what number does it give back?  Now draw a point directly above or below the point on the horizontal line that means zero (remember, that’s the point where the lines cross).  How far up or down you draw the line is decided by what the function gives you back.  Now do the same thing for 1, and for 2, and so on…

Finally, once you’ve got a bunch of points, connect them with a smooth line.  That line is how you draw that function.

### Example

Let’s try an example.  We’re going to draw the function

`f t = t/2 - 2`

That means the function is called f, its parameter (the number you give it) is called t, and the number it gives you back is half of t, minus 2.

Let’s draw the lines like we did before, and label the points counting by one in both ways:

The next step is to figure out some values of the function, and draw them as points on the graph:

`f t = t/2 - 2`
```f  0 =  0/2 - 2 = 0.0 - 2 = -2.0
f  1 =  1/2 - 2 = 0.5 - 2 = -1.5
f  2 =  2/2 - 2 = 1.0 - 2 = -1.0
f  3 =  3/2 - 2 = 1.5 - 2 = -0.5
f  4 =  4/2 - 2 = 2.0 - 2 =  0.0
f  5 =  5/2 - 2 = 2.5 - 2 =  0.5
f  6 =  6/2 - 2 = 3.0 - 2 =  1.0
f  7 =  7/2 - 2 = 3.5 - 2 =  1.5
f  8 =  8/2 - 2 = 4.0 - 2 =  2.0
f  9 =  9/2 - 2 = 4.5 - 2 =  2.5
f 10 = 10/2 - 2 = 5.0 - 2 =  3.0
f 11 = 11/2 - 2 = 5.5 - 2 =  3.5
f 12 = 12/2 - 2 = 6.0 - 2 =  4.0
f 13 = 13/2 - 2 = 6.5 - 2 =  4.5```

Here’s the graph with the line that connects those points:

### How to Read the Drawing

Looking at the graph, you can get a good feeling for what that function does.  Imagine you’re always moving to bigger and bigger numbers of seconds since the program started (because you are!).  Then this function will keep getting bigger and bigger forever.  You can also see that it will keep getting bigger at the same speed.  And you can see that it starts out being -2, and then after 4 seconds it’s 0, and it keeps going up from there.

So what does that mean?

• If you say rotate (t/2-2), that means start out rotated a little bit clockwise, and then turn counter-clockwise at a constant speed forever.
• If you say translate (t/2-2) 0, that means start out a little to the left, then move right at a constant speed forever.
• and so on…

## Practice Drawing Functions on Numbers

In class on Tuesday, we did this worksheet together, where we practiced drawing functions that use numbers.

graphs_worksheet

## Some Useful Functions on Numbers

You might notice at the end of the worksheet a few functions that we haven’t used yet that are useful:

• min and max.  These functions actually take two numbers as parameters, and they return one of the two numbers you give them.  So min gives you the smaller of the two numbers, and max gives you the larger of the two numbers.
• sin.  This function, which is pronounced like “sign”, is useful for making things move back and forth.  It is way more interesting than just that, but we’ll save the more interesting stuff for high school trigonometry classes.  All we want it for is to make things move back and forth.  Keep in mind that sin itself only goes back and forth between -1 and 1, so you probably want to multiple the answer by something bigger!

Want to see what the sin function looks like?  Here you go:

Because the Little School is off next week for a inter-term break, it will be two weeks until my next summary!  Never fear, though, I’ve got something for you to work on.

Your task is to make an animation of an amusement park ride.  Try to get several kinds of movement in there: rotating in circles, moving back and forth, and anything else you can do!  Those of us in my class are going to make these:

• Skyler: Roller coaster
• Grant: Bungee Jump Ride
• Marcello: Ferris Wheel
• Sophia: Tilt-a-Whirl
• Sue: Swinging Pirate Ship
• Me: Kids Jumping Rope (the example from week 7, but I might tweak it a little)

We’re planning to put them together into a gigantic amusement park picture when we’re done.  If you have friends doing this at the same time, you can, too!  (Do you know how?  It’s just like top-down design: get everyone to send you their programs, but call them something other than animation, then scale them, move them to different places, and combine them using pictures.)

Good luck!  And as always, use the comments to ask for help if you’re stuck.

# Where We Are

This is the summary of week 7 of my Haskell class for children, aimed at ages 11 through 13 or so.  You can go back and review the previous weeks to catch up.

We’ve now spent six weeks learning some of the Haskell programming language, and making various pictures, from simple stuff to some pretty complicated drawings.  Now it’s time for the next big step: animations!

# Using gloss-web for Animations

We’ve done all of our programming using the gloss-web web site at http://dac4.designacourse.com:8000, where you can program and look at the result in a web browser.  So far, everything we’ve done has been in the “Picture” portion of the web site, which you get to by clicking the picture button:

Now we’re ready to move on to the next type of program.  So to get started, click the “Animate” button instead.

This page will look very nearly the same, but don’t be fooled!  The web site now expects from you a different kind of program: one that describes a picture that moves over time.

You’ll remember that the picture mode expected you write a definition for a variable called picture.  Everything else in your program was just there to help you define what picture meant, and when you finished, the program would run by looking up the definition of picture, and drawing it.  Your other definitions were useful only because they let you use those new words to define picture more easily.

The same thing is going on here, but there are two changes:

1. Instead of picture, you’re defining a word called animation.
2. Instead of being a description of a picture, animation is a function.  Like all functions, it has a parameter, which is the amount of time that’s passed.

Warning: I’ve said from the beginning not to use Internet Explorer for the programming web site.  It’s probably worked so far if you didn’t listen to me.  But now it will not work any more, so you’ll need to use something else: Firefox, Chrome, Safari, Opera… take your pick, but Internet Explorer won’t work.

Let’s jump in with some examples.

## Example 1: Rotating a square

The first example program we’ll write is the one that is given to you by the web site:

`import Graphics.Gloss`
`animation t = rotate (60 * t) (rectangleSolid 100 100)`

Here’s how to think about what that means.Think of t as standing for the number of seconds it’s been since you clicked the Run button.

At the very beginning of your animation, it’s been 0 seconds since you pressed Run.  So the program is saying the same thing as: rotate (60*0) (rectangleSolid 100 100).  Remember that * means multiplication.  Of course, 60 times 0 is 0, so this is just rotate 0 (rectangleSolid 100 100).  It draws a rectangle that hasn’t been rotated at all.

But then some time passes.  After half of a second, now t is 0.5.  Now the picture your program is drawing is rotate (60*0.5) (rectangleSolid 100 100).  What is 60 times one half?  It’s 30.  So now the picture is rotate 30 (rectangleSolid 100 100), and it will draw a rectangle rotated by 30 degrees.  This will continue, too.  After a full second, t is 1, and 60 times 1 is 60, so the rectangle will be rotated by 60 degrees.  After 2 seconds, it will be rotated by 60 times 2, or 120 degrees.  As t gets bigger, the rectangle will be rotated more.

Okay, here’s a little quiz: how long will it take for the rectangle to turn all the way around, a full 360 degrees?  That shouldn’t be too hard: you want to find the number that will give 360 when it’s multiplied by 60.  That’s how many seconds it will take.

What about after that?  Can you rotate something more than 360 degrees?  Sure, you can… but you can’t tell that you did it!  Rotating 360 degrees looks just like leaving it alone.  So, for example, when it’s rotated 390 degrees, that’s the same as just rotating 30.  (If you were thinking about this, you might have noticed that you actually can’t even tell if a square has been rotated 90 degrees!  That’s because of the symmetry of the square.  But you can’t tell if any shape has been rotated 360 degrees, no matter if it has symmetry or not.)

Try this example on the web site, and make sure it looks the way you expected.

## Example 2: Changing the speed

Let’s make a small modification to the example earlier.  We’ll make the square rotate faster:

`import Graphics.Gloss`
`animation t = rotate (100 * t) (rectangleWire 100 100)`

Just like before, t stands for the number of seconds since you clicked Run.  At the very beginning, t is zero, and zero times 100 is still zero.  So it starts in the same place.  But now look what happens: after half a second, it’s rotated by 50 degrees.  After a full second, it’s rotated by 100 degrees.  It will only take about three and a half seconds to make a full turn.

## Example 3: Starting at a different angle

Now let’s try to change the angle it starts at, so that it started standing on one point like a diamond.

`import Graphics.Gloss`
`animation t = rotate (100 * t + 45) (rectangleWire 100 100)`

Okay, what’s that when t is zero?  It’s rotate 45 (rectangleWire 100 100).  So the square will start out turned on one point.  It will still rotate at the same speed as before, though: 100 degress every second.  Try that and see what it looks like.

## Example 4: Moving

Now let’s try moving something instead of rotating it.

`import Graphics.Gloss`
`animation t = translate (50 * t) 0 (circle 25)`

Take a moment and try to guess what that will look like.

To figure it out, let’s look at the picture we’ll get at different times.  When the animation first starts, it’s been 0 seconds, and t is 0.  Then this is translate 0 0 (circle 25).  That won’t move the circle at all, so it will still be in the middle of the box.  But now when t is 1 (after the animation has been going for a full second), it will become translate 50 0 (circle 25), so the circle will be a bit off to the right.  In fact, the circle keeps moving right until it runs right off the screen (and even afterward, but then you can’t see it any more).

Try it!

## Example 5: Moving faster

Can you guess how to make the circle move faster?  If you guessed that we want to multiply t by a higher number, you’re right!

`import Graphics.Gloss`
`animation t = translate (100 * t) 0 (circle 25)`

The circle will still start in the middle. (Why?)  But now after one second, it will have moved twice as far.  It’s moving faster.

We won’t do it as an example, but what if you wanted the circle to start on the left side of the screen?  Hint: it works a lot like example 3!

## Example 6: Changing the size

What if you want something to get larger as time goes on?  You can do that, too.  Here’s an example:

`import Graphics.Gloss`
`animation t = circle (20 * t)`

Once again, t stands for the number of seconds since you pressed Run.  At the very beginning, your picture will be circle (20 * 0), which is the same thing as circle 0.  A circle with a radius of 0 is too small to see, so you won’t see anything.  But after half a second, it becomes circle (20 * 0.5), which is circle 10, and you will see a circle with a radius of 10.  The circle will keep getting larger: after ten seconds, it will be circle 200.  Eventually, if you’re patient enough, it will grow too big to even show up on the screen.

Try that, and see if it does what you expected.

(You could have also written that using scale: animation t = scale t t (circle 20).  Do you see why those two programs should do the same thing?)

## Example 7: Rotating around another point

Sometimes we might want something to rotate, but around the middle of the whole picture (or part of a picture), and not just around its own middle.  The trick is to move it (with translate), and then rotate the picture that you get as a result of that.

`import Graphics.Gloss`
`animation t = rotate (60 * t) (translate 100 0 (circleSolid 25))`

See if you can work out what that will look like at different times, and then try it out and check yourself.

## Animations and List Comprehensions and Functions

You might have noticed that a lot of the things we’re doing here seem very similar to what we did with list comprehensions.  You’d be right!

Both times, we had variables, and we got different pictures because those variables got different values.  The difference is that with list comprehensions, we put all of those different pictures together at the same time.  Now we’re using different pictures at different times.  But the idea is the same: you use variables to represent numbers that you don’t know yet, and then you can build versions of your picture where those variables mean something different.

We’ve actually used variables like that three times:

• When we defined functions (like awesome), the parameters got names, and you used those names in the function.
• In list comprehensions, you used the funny backward arrow: <-, to pick a name and arrange for it to get lots of different values.
• Now, in animations, you’re again defining a function: a special one, where the parameter is the time.

This is something that will keep happening.  Variables are very important, so you should get used to seeing expressions that have variables in them, and doing something called “substitution”.  That just means answering the question “If t is 5, what does this work out to?”

# Top Down Design With Animations

With pictures, we worked on organizing our program by top down design: we started by saying what picture meant, but we sometimes used other words the computer doesn’t know yet.  Then we went back in and filled in what those words meant.  We just kept this up until the program was done.  The nice thing about top-down design was this: you didn’t have to think about your entire program at once.  You could just think about one piece at a time.

We’d like to keep doing top-down design with animations, too.  There’s one thing we have to figure out, though, and that’s what to do with t.  Here’s what we’ll do:

• When we’re defining a word, if its a piece of the picture that, just looking at that one piece, will have some movement, then we’ll make it a function, taking a parameter called t.
• When we’re using it later on, we’ll pass t for that parameter.

It’s important to keep these consistent: if you define a function with a parameter, then you also have to give it that parameter when you use the function.  If you define a variable without a parameter, then you aren’t allowed to give it a parameter when you use it.

Let’s look at an example: here’s a program to draw a clock:

```import Graphics.Gloss

animation t = clock t

clock t = pictures [
backPlate,
minuteHand t,
secondHand t
]

backPlate = color (dark white) (circleSolid 250)

minuteHand t = rotate (-0.1 * t) (line [(0,0), (0,250)])

secondHand t = rotate (-6 * t) (line [(0,0), (0,250)])```

We’ll break it down piece by piece:

1. First, we defined the animation function.  When you’re working in animation mode, you always have to define this, and it always has the parameter t, that means how many seconds since it started.  We say that the animation is a clock.  The clock will have moving parts, so we pass along t.
2. Since we gave the time, t, to clock earlier as a parameter, our definition of clock has to say it has a parameter, too.  A clock consists of three parts: a back plate, a minute hand, and a second hand.  The back plate does not move, so we don’t pass along t.  But the minute hand and second hand do move, so we’ll be passing the time along to those.
3. Next we define backPlate.  Remember we didn’t give it a t parameter because it won’t be moving, so this is just a variable.
4. Now we define minuteHand.  We did give it a parameter, so now we have to say it gets a parameter.  And just like in the earlier examples, we can use that parameter t to make it rotate.  We want the minute hand to rotate 360 degrees every hour, and an hour is 3600 seconds.  So that means we want it to move only a tenth of a degree every second.  Also, we’d like it to move clockwise, so that number has to be negative.  (Remember, positive rotations are counter-clockwise.)
5. Finally, we define secondHand.  It needs a parameter, too, so we give it the t parameter.  The definition looks the same, but now we want it to rotate 360 degrees every minute (60 seconds).  That works out to 6 degrees every second, and it’s still negative so that the rotation is clockwise.

Hopefully, that doesn’t look too bad!  It’s just the same kind of top-down design we’ve been doing, except with some time thrown in to keep things moving.  You have to ask yourself whether each part has movement in it or not, and you have to consistent about the answer.

## This week’s assignment

The assignment we’re working on this week is to make a working model of the solar system.  That is, put the sun in the middle, and the planets around it, and have them rotate around the sun.  A few notes:

• It doesn’t need to be to scale.  In fact, the planets are so far apart, and so small compared to the distance between them, that if you try to draw everything to scale, you won’t even be able to see it!  So just pick what looks good.
• If you are ambitious, try to add at least one moon, and give Saturn its rings.The hint here is that moons and rings aren’t too hard, as long as you’re using top-down design.  For example, you should have something called saturn, and instead of making it a circle, make it a pair of circles with one of them stretched a bit.

Now suppose you’re adding a moon to earth, you probably want a function called something like earthSystem that represents the earth and its moon together.  Since the moon is moving around the earth, it should be a function and have a parameter called t.  When you’re defining earthSystem, you’ll probably want even more variables called earth and moon.  These will probably just be colored circles.

• Our class here in Colorado Springs actually all decided to make up their own solar system with different planet names.  That’s fine, too.  In fact, the computer doesn’t care what you name things.

Good luck!  And feel free to ask in the comments for help.

# Just for fun…

If you’re bored, try this animation.  It’s a preview of what’s coming in the next couple weeks.

```import Graphics.Gloss

animation t = pictures [
jumprope t,
translate (-210) 0 stickFigure,
translate ( 210) 0 stickFigure,
jumper t
]

jumprope t = scale 1.75 (1.1 * sin t) rope

rope = line [ (x, 100 * cos (0.015 * x)) | x <- [-100, -75 .. 100 ] ]

stickFigure = pictures [
line [ (-35, -100), (0, -25) ],
line [ ( 35, -100), (0, -25) ],
line [ (  0,  -25), (0,  50) ],
line [ (-35,    0), (0,  40) ],
line [ ( 35,    0), (0,  40) ],
translate 0 75 (circle 25)
]

jumper t = translate 0 (max 0 (-50 * sin t)) stickFigure```

That’s all for this week.

(This is from last week.  Yes, I’m really late in posting this… sorry!  This week’s summary will be up in a couple days.)

# Practice Time

Welcome to the week 6 summary of Haskell for Kids, my middle school level (that is, ages 12 – 13 ish) programming class using Haskell and Gloss at the Little School on Vermijo.  You can go back and review weeks 1, 2, 3, 4, and 5 if you like.

This week was time for practice.  Instead of introducing any new ideas, I’ll just post the practice activity we did together in class on Tuesday.  The way we practiced was very simple: I drew pictures, and we tried to write descriptions of those pictures.  Rather than waste time, let’s just jump right into it.  It might help to download (and maybe print out) the PDF file from the end of week 5 (follow the link earlier) for a reminder of how to write list comprehensions.

I’m not including answers, because it’s too easy to just read ahead!  If you can’t figure one of them out, feel free to ask for help in the comments.

### Practice 1

Hints: None!  Hopefully this one is easy.

### Practice 2

Hints: The parameter to circle is a number.  Use the variable from the list comprehension for that.

### Practice 3

Hints: This one should also be easy.  It’s just a stepping stone to the next practice.

### Practice 4

Hint: The list comprehension variable tells you how far to translate.

### Practice 5

Hint: Don’t do this with rotate.  You can change just one thing from practice 4 and make this work.  Remember that you can use the list comprehension variable more than once.

### Practice 6

Hint: Remember that if you translate something first and then rotate it, it will be rotated around the middle of the picture.

### Practice 7

Hint: Here you’ll want to use two variables in your list comprehension.  One of the examples from the reference page shows you how to do this.

### Practice 8

Hint: Again you want two variables, but this time one of them will be used in translate and the other one in rotate.

# Projects

In addition to this, we just worked on our list comprehension projects.  If you remember from last week, the project was to pick something repetitive and draw it.  I suggested a U.S. flag if you’re in the U.S. and don’t have another idea.  Some of the other projects kids from our class came up with were an iPhone with a grid of icons, a keyboard (the musical type!), and a galaxy with spiral arms and a background of stars.  So be creative!

Oh, and I have to show off Sophia’s keyboard, because she worked really, really hard on it, and I’m very impressed.  It’s a great use of list comprehensions, too.  Here goes…

# Functions and Variables!

Welcome to the week 5 summary of my Haskell class for kids.  You can go back and read the previous weeks summaries, if you like:

Our theme this week will be functions and variables.

## Section 1: How to Draw an Awesome Elephant

We started with a simple example.  We already know how to draw a star:

```star = polygon [
( -75, -100),
(   0,   87),
(  75, -100),
(-100,   25),
( 100,   25),
( -75, -100)
]```

and Sophia has figured out how to draw an elephant (this is one of her early versions, actually, but I picked it because it’s shorter; you don’t need to understand it):

```elephant = pictures [
rotate (-20) (scale 3 2 (translate 30 40 (circleSolid 25))),
translate 150 (-20) (rectangleSolid 40 80),
translate (-10) 40 (scale 1.5 1 (circleSolid 80)),
translate 50 (-50)(rectangleSolid 40 70),
translate (-60) (-50) (rectangleSolid 40 70),
translate (-140) 50 (rotate 100 (rectangleSolid 10 40))
]```

But now we want to draw a really awesome star.  Being “awesome”, of course, means being twice as large, and the color chartreuse.

`awesomeStar     = scale 2 2 (color chartreuse star)`
`awesomeElephant = scale 2 2 (color chartreuse elephant)`

and

But, by now, you can probably guess that I can draw an awesome version of any picture.  There are awesome spaceships, awesome shoes, awesome bicycles… give me any picture at all, and I can tell you how to draw an awesome one: you draw it twice as big, and make it chartreuse.  It will get tiresome to keep repeating ourselves, but luckily, Haskell lets us say this just once:

`awesome x = scale 2 2 (color chartreuse x)`

Now we don’t need to define a bunch of variables like awesomeStar and awesomeElephant.  Instead, we can just write awesome star, with a space in between the two!

We’ve seen things like this before: awesome is called a function, and the thing that we’re making awesome is called its argument.  But up until now, we’d only used functions that other people gave us… like rotate and translate in the Gloss library.  Now, we know how to write definitions for our own functions.

To sum up, we can write a function because:

1. Given any thing, we know how to make it awesome.
2. It follows a formula: scale 2 2 (color chartreuse ____________) where you just fill in the blank.

If both of those are true, you can write a function definition.  It looks like like the variable definitions we’ve written before, except that it has parameters.  A parameter is any word that comes before the equal sign (=), except for the first one.  In the function we wrote a minute ago, we called the parameter x.  Parameters are just placeholders, so when you use the function, you’ll give it an argument, that argument gets stuck in where ever that variable name pops up.

We also talked about what it means to be cute, and came up with the following:

`cute x = scale 0.5 0.5 (color purple x)`

Let’s check our assumptions: given any shape you choose to define, we can draw a cute one.  It follows a definite formula (make it half the size, and color it purple).  And so we wrote a definition where the function is called cute, and the parameter is called x.  If you wanted to draw a cute elephant, you could define picture like this: picture = cute elephant.  There, the function is cute and the argument is elephant, so to figure out what that means you just replace x with elephant every time it shows up in the function definition for cute!

## Section 2: In which elephants can move their tails…

Let’s look at another function.  We know how to draw an elephant… but there’s one problem.  No matter where we draw an elephant, its tail is always sticking out at exactly the same angle.  Suppose we want to be able to draw an elephant with its tail sticking in whatever direction we like.

It turns out that almost all of drawing an elephant will remain the same, but there’s one rotate where we’ll want to change the angle.  So once again, we have:

1. For any angle, we can draw an elephant with its tail at that angle.
2. How we draw an elephant follows the same formula each time, except for a different number in that one place.

Sounds like a job for a function!

```elephant angle = pictures [
rotate (-20) (scale 3 2 (translate 30 40 (circleSolid 25))),
translate 150 (-20) (rectangleSolid 40 80),
translate (-10) 40 (scale 1.5 1 (circleSolid 80)),
translate 50 (-50)(rectangleSolid 40 70),
translate (-60) (-50) (rectangleSolid 40 70),
translate (-125) 50 (rotate angle (translate 0 20 (rectangleSolid 10 40)))
]```

See how that worked?  Most of the elephant stayed the same, but the rotate in the last line uses the parameter, angle.  So whatever number we give it decides with way the tail points.  It could be straight up…

`picture = elephant 0`

or it could be mostly down…

`picture = elephant 160`

So once again, we’re able to use functions: this time to say how to draw an elephant, but leave until later the question of which direction its tail should be pointing.

## Section 3: Lists, Lists Everywhere

The interesting thing about functions was that they have parameters, which are special variables that can have different values depending on how you use the function.  There’s another way that something similar can happen, and it’s in lists.  So we’ll finish off by looking at some more kinds of lists.

The lists we’ve used so far have all looked something like this:

`[ 1, 2, 3, 4, 5 ]`

In other words, a list has always had an opening bracket, then some elements (that is, things in the list) separated by commas, and finally a closing bracket.  The things in the list haven’t been numbers… we’ve worked with lists of pictures, and lists of points!  You can have lists of whatever you want, but the form is the same: you still have the brackets and the commas.  We can call these “simple lists”, because, they are pretty easy to use.

A second kind of list that will come in handy, that we haven’t used before, is a range.  That looks like this:

`[ 1 .. 10 ]`

It always has an opening bracket, a first element, two dots in a row, and then a final element, and a closing bracket.  This kind of list counts for you.  The things inside (for now, at least) always have to be numbers so that you can count… and the computer will fill in the middle of the list for you.  In this case, the list we defined is the same as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].  The range is just a shorthand.

There’s one more simple trick we can play, too: we can give the first two elements, and the computer will continue the pattern:

`[ 2, 4 .. 10 ]`

This look almost like a range, except that we’ve given the first two elements, instead of the just the first one.  The computer will notice that we skipped forward by two, and will keep doing that, so that list is the same as [2, 4, 6, 8, 10]!

Finally, we get to the most interesting kind of list of all: called a list comprehension.  Here’s an example:

`[ x + 7 | x <- [1 .. 5] ]`

This has quite a few parts, so let’s go through them carefully:

• It starts with an opening bracket, just like all lists.
• Next is an expression.  Notice that the expression has a variable x that we haven’t mentioned yet.  That’s okay, it’s coming later.
• In the middle, there’s a vertical bar (shift + backslash).  That separates the expression from the next part.
• Now we have a sort of definition of x, except we say that x is any thing from another list!  We do that with a backwards arrow, which is typed as a less-than sign, followed by a dash.
• Finally, there’s a closing bracket.

What this means is: give me a list of all values of (x+7), where x is any of the numbers in that list.  So this is equivalent to [1+7, 2+7, 3+7, 4+7, 5+7]… and of course that is the same as [8, 9, 10, 11, 12].

This last kind of list is very, very interesting; but maybe right now it just looks very complicated and you can’t see why.  To see how it’s interesting, we’ll start writing some lists of pictures, instead of just numbers.

## Section 4: Combining List Comprehensions and Pictures

The last thing we did this week is combine pictures and list comprehensions to make some interesting pictures.  I’ll give you a bunch of examples, but not the pictures they draw.  Your task is to first try to guess what the picture will look like, and then try them out using the gloss programming web site and check your guesses.

I’d very strongly encourage you to take this seriously… use graph paper, work it out, and do your best to figure out what is going to be drawn before you run the program and check.

First example:

```picture = pictures [
circle x
| x <- [ 10, 20 .. 100 ]
]```

Second example:

```picture = pictures [
translate x 0 (circle 20)
| x <- [ 0, 10 .. 100 ]
]```

Third example

```picture = pictures [
translate x 0 (circle x)
| x <- [ 10, 20 .. 100 ]
]```

Fourth example:

```picture = pictures [
rotate x (rectangleWire 300 300)
| x <- [ 0, 10 .. 90 ]
]```

Fifth example:

```picture = pictures [
translate x 0 (rotate x (rectangleWire 300 300))
| x <- [ -45, -35 .. 45 ]
]```

We can also put several different variables on the right side of the vertical bar, separated by commas.  In that case, we’ll get something in the list for each possible combination of those variables!  We can use that, too…

Sixth example:

```picture = pictures [
translate x y (circle 10)
| x <- [ -200, -100 .. 200 ],
y <- [ -200, -100 .. 200 ]
]```

Seventh example:

```picture = pictures [
rotate angle (translate x 0 (circle 10))
| x     <- [50, 100 .. 200 ],
angle <- [ 0,  45 .. 360 ]
]```

Eighth example:

```picture = pictures [
rotate angle (translate (5*x) 0 (circle x))
| x     <- [10, 20 ..  40 ],
angle <- [ 0, 45 .. 360 ]
]```

As you can see, you can use list comprehensions to make lots of really cool pictures where it would be really tedious to write out each shape the way we’ve been doing before.

Your assignment this week is to pick a picture with a lot of repetition that you can draw with list comprehensions, and build it.  If you are in the United States and don’t have another idea, a really good one is the American flag!

Hints:

• There’s a program to draw a star at the beginning of this summary.  You can copy the star part from that if you like.
• You’ll probably have to draw the stars in two groups: first, there’s a 5-row, 6-column bigger grid, and then there’s a 4-row, 5-column smaller grid inside of that.

You don’t have to draw a flag, though!  Especially if you’re not in the United States, your flag probably doesn’t repeat as much as ours, so you’ll want to pick something different.  Just pick something you can draw by using list comprehensions to make lists of pictures.

Have fun!

## A Reference

One last thing… I’ve put together a reference card about the recent things we’ve done: lines, polygons, and types of lists.  This might be a good thing to keep around.  Click below to grab a copy.

# New Student!

First of all, we gained a student in my class, so we all welcomed Skyler!  We’re three weeks in, but this gave us a great chance to go back over some of the basic ideas we’ve already seen.  These include:

1. The first week, we talked about what computer programming is, what a compiler is, and what a library does for you.  We also introduced the basics of programming using the Haskell programming language and the Gloss library, and we played around.  So we reviewed the basics of that.  Here’s a link to the Week 1 Summary.
2. The second week, we talked about the basic structure of a program, including what an import statement means, how to write definitions of variables, and the idea of expressions.  We also looked at how useful it is to stay organized and make sure everything in your program is where it belongs.  Here’s a link to the Week 2 Summary.
3. Finally, the third week, we talked about cartesian (x,y) coordinates and lines and polygons, and we practiced “playing computer” and predicting what the computer is going to draw when it sees programs we made up.  Here’s a link to the Week 3 Summary.

Skyler joining gave us a chance to go back and review that, and practice explaining it to someone new.  I think most people learned something new of their own, too.

# Practicing Top-Down Design

Another thing we did this week was practice some of the ideas we’ve touched on briefly in the past:

• Top-down design
• Organizing and naming things
• Writing stubs

We did this by working through an example in class, in great detail.  I’ll try to reproduce that here.  You can follow along, as always, at http://dac4.designacourse.com:8000/  Remember, the point of this isn’t just to skip ahead and look at the final result: it’s to follow through the steps of how we got there.  We used techniques that you can use to try to write your own programs, too!

It does get repetitive, though, so at each step (except the last), I’ve bolded the parts of the program that are new, so you can generally ignore anything that’s not in bold because you’ve seen it before.

### The Goal

Our goal will be to draw a dinner plate.  Here’s a whiteboard drawing of our goal:

We’ll start out by writing a basic program to draw an empty picture.  We may not have used it before, but blank is defined by Gloss to be an empty picture.

```import Graphics.Gloss

picture = blank```

If we run this program, the result looks rather boring…

So far, so… boring.  But there’s something worth pointing out.  Defining picture to be blank was called a “stub”.  We just stuck something in to make the program complete, knowing it was obviously not enough.  That’s okay, so long as we remember the places we’ve used stubs so we can go back and fill them in later.

The first thing we’ll do is declare that our picture is a dinner.  That looks something like this.  We’ll also start adding comments (remember, those of bits of the program that are ignored by the computer) to remind ourselves where we’ve got stubs.

```import Graphics.Gloss

picture = dinner
dinner = blank -- stub ```

This looks the same as before; we’ve just said that the picture is a dinner… and that a dinner is blank.  It might seem pointless, but don’t underestimate the chance to name things!  This will come in handy later.

Let’s fill in the stub for dinner with the major parts of the dinner we’d like to draw.  If you look at the plan, you can see it’s roughly divided into a plate, some food, a knife, and a fork.  I’ll throw in a table, too, which is just the background for the entire image.  Here’s our attempt to expand on the program:

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
fork,
knife
]

table = blank -- stub
plate = blank -- stub
food = blank -- stub
fork = blank -- stub
knife = blank -- stub```

This might not look impressive when it’s done, but we’re working on understanding how to break down the picture into pieces.  Let’s pick out a few easy pieces to draw, now.  First, the table is just a 500 by 500 rectangle (in other words, the entire screen), colored a good table color, like brown.

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
fork,
knife
]

table = color brown (rectangleSolid 500 500)
plate = blank  -- stub
food  = blank  -- stub
fork  = blank  -- stub
knife = blank  -- stub```

Let’s compile and run that…

`Not in scope: `brown'`

Oops!  We used the color brown, but that’s not defined by Gloss.  We can define it, though.  Brown is, generally speaking, a dark orange, so let’s say so:

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
fork,
knife
]

table = color brown (rectangleSolid 500 500)
plate = blank  -- stub
food  = blank  -- stub
fork  = blank  -- stub
knife = blank  -- stub

brown = dark orange```

Now we’ll try again.

Looks good!  Time to add the plate.  We want to draw a rim on the plate, so it will consist of two circles — one on top of the other, and a little smaller.  We’ll also want two new colors: gray and lightGray.  This shouldn’t be difficult, so we’ll write it.

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
fork,
knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray (circleSolid 175),
color lightGray (circleSolid 150)
]

food  = blank  -- stub
fork  = blank  -- stub
knife = blank  -- stub

brown     = dark orange
lightGray = dark white
gray = dark lightGray```

I did something a little tricky with the colors.  I could have defined gray to be dark (dark white), but it was easier to use the other color, lightGray, that I’d already defined.  Either one would mean the same thing.  Can you see why?

We’ll now build and run this program, and check the result.

As you can see, this is coming along fine.  Time to do something about that silverware that’s stubbed out.  What do we know about it?  Let’s make a list:

• We want a fork and a knife, both.
• We want them to be in the middle vertically, but on different sides, about 200 pixels over.
• They will be much taller than they are wide… maybe 300 pixels tall, but only 50 wide.

We’ll stop there, rather than trying to do everything at once.  Remember, the idea is to work in small steps, filling in a few details at a time.  So for now, we’ll ignore the unique shapes of forks and knives, and just make them rectangles.  Because where we put the fork and knife isn’t really a part of what it means to be a fork or knife, those translations should go in dinner, not fork or knife.  The result looks like this.

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
translate ( 200) 0 fork,
translate (-200) 0 knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray      (circleSolid 175),
color lightGray (circleSolid 150)
]

food  = blank                 -- stub
fork = rectangleWire 50 300 -- stub
knife = rectangleWire 50 300 -- stub

brown     = dark orange
lightGray = dark white
gray      = dark lightGray```

Notice that I’ve stilled marked fork and knife as stubs.  They are!  That’s certainly not what they look like.  But it just helped to draw an outline of the region of the plate where they belong.  Let’s compile and run this, and see what happens.

It’s about time we start filling in the food.  We’ll start out by breaking it down into the three main pieces, and then again stub them out with outlines rather than get into the details of what each piece looks like.  Each piece of food is translated and rotated a little.

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
translate ( 200) 0 fork,
translate (-200) 0 knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray      (circleSolid 175),
color lightGray (circleSolid 150)
]

food = pictures [
translate (-50) ( 50) (rotate ( 45) carrot),
translate (-20) (-40) (rotate ( 20) broccoli),
translate ( 60) (-30) (rotate (-10) broccoli)
]

carrot = rectangleWire 40 80 -- stub
broccoli = rectangleWire 80 80 -- stub
fork     = rectangleWire 50 300  -- stub
knife    = rectangleWire 50 300  -- stub

brown     = dark orange
lightGray = dark white
gray      = dark lightGray```

Don’t worry if you couldn’t figure out all those numbers right off!  When we wrote this in class, we had to guess and then tweak them until the rectangles ended up in about the right places.  Being able to do that before we worry about the details of what broccoli is shaped like is one of the reasons we like stubs like this!  (Also, don’t worry if you didn’t know how to spell broccoli.  I had to look it up, too.)

Let’s run this and see what it looks like.

We’re now going to play our next trick.  We’d like to focus on how to draw a carrot.  But since the carrot is translated and rotated, it’s hard for us to focus on just that piece.  Remember when we wrote picture = dinner earlier?  I promised that would come in handy!  We’re going to, just for now, change that to say picture = carrot.  Our program now looks like this:

```import Graphics.Gloss

picture = carrot

dinner = pictures [
table,
plate,
food,
translate ( 200) 0 fork,
translate (-200) 0 knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray      (circleSolid 175),
color lightGray (circleSolid 150)
]

food = pictures [
translate (-50) ( 50) (rotate ( 45) carrot),
translate (-20) (-40) (rotate ( 20) broccoli),
translate ( 60) (-30) (rotate (-10) broccoli)
]

carrot   = rectangleWire 40  80  -- stub
broccoli = rectangleWire 80  80  -- stub
fork     = rectangleWire 50 300  -- stub
knife    = rectangleWire 50 300  -- stub

brown     = dark orange
lightGray = dark white
gray      = dark lightGray```

When we run this, we’ll have told the computer all about dinners and forks and knives and everything… but in the end, only asked it to draw a carrot.  That’s fine; the computer is happy to ignore our definitions of variables that we don’t really use!  The result looks like this.

So we’ve gotten rid of everything except the carrot, which of course looks like just a rectangle for now.  Having escaped from the distractions of forks and broccoli, it shouldn’t be too hard to tell what a carrot is!  It’s just a polygon colored orange.  After some experimentation, you might end up with this:

```import Graphics.Gloss

picture = carrot

dinner = pictures [
table,
plate,
food,
translate ( 200) 0 fork,
translate (-200) 0 knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray      (circleSolid 175),
color lightGray (circleSolid 150)
]

food = pictures [
translate (-50) ( 50) (rotate ( 45) carrot),
translate (-20) (-40) (rotate ( 20) broccoli),
translate ( 60) (-30) (rotate (-10) broccoli)
]

carrot = color orange (polygon [
(-5, -40), (-20, 40), (20, 40), (5, -40)
])

broccoli = rectangleWire 80  80  -- stub
fork     = rectangleWire 50 300  -- stub
knife    = rectangleWire 50 300  -- stub

brown     = dark orange
lightGray = dark white
gray      = dark lightGray```

That looks like this:

Now, having gotten the look of a carrot under control, let’s change the definition of picture, so that the entire dinner will be drawn again.

```import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,
translate ( 200) 0 fork,
translate (-200) 0 knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray      (circleSolid 175),
color lightGray (circleSolid 150)
]

food = pictures [
translate (-50) ( 50) (rotate ( 45) carrot),
translate (-20) (-40) (rotate ( 20) broccoli),
translate ( 60) (-30) (rotate (-10) broccoli)
]

carrot = color orange (polygon [
(-5, -40), (-20, 40), (20, 40), (5, -40)
])

broccoli = rectangleWire 80  80  -- stub
fork     = rectangleWire 50 300  -- stub
knife    = rectangleWire 50 300  -- stub

brown     = dark orange
lightGray = dark white
gray      = dark lightGray```

Hopefully, you can see how this will end up.  One by one, for each of the remaining pieces of the program, we’ll do three things:

1. Change the definition of picture to focus on that piece.
2. Write a program to properly draw that piece.
3. Change the definition of picture again to draw the entire dinner.

In the interest of space, I’m skipping the remaining steps, but here’s the program we ended up with:

```{-
Picture of a dinner plate

This program draws a dinner plate, with several food items and silverware.
-}

import Graphics.Gloss

picture = dinner

dinner = pictures [
table,
plate,
food,

-- Silverware:
translate ( 200) 0 fork,
translate (-200) 0 knife
]

table = color brown (rectangleSolid 500 500)

plate = pictures [
color gray      (circleSolid 175),            -- rim
color lightGray (circleSolid 150)             -- center
]

food = pictures [
translate (-50) ( 50) (rotate   45  carrot),
translate (-20) (-40) (rotate   20  broccoli),
translate ( 60) (-30) (rotate (-10) broccoli)
]

carrot = color orange (polygon [
(-5, -40), (-20, 40), (20, 40), (5, -40)
])

broccoli = color (dark green) (pictures [
translate (  0) (-15) (rectangleSolid 30 50), -- base
translate (-15) (  0) (circleSolid 25),       -- flower
translate ( 15) (  0) (circleSolid 25),       -- flower
translate (  0) ( 15) (circleSolid 25)        -- flower
])

fork  = color lightGray (pictures [
rectangleSolid 10 250,                        -- handle
translate (  0) ( 80) (rectangleSolid 40 10), -- base
translate (-15) (100) (rectangleSolid 10 45), -- left prong
translate ( 15) (100) (rectangleSolid 10 45)  -- right prong
])

knife = color lightGray (pictures [
translate 0 (-25) (rectangleSolid 30 200),    -- handle
polygon [ (-15,  75),
( -5, 105),
( 15, 125),
( 15,  75) ]                        -- blade
])

{-
Some colors that are used in the picture:
-}
brown     = dark orange
lightGray = dark white
gray      = dark lightGray```

(We also added some comments to explain a little more and divide up the program into sections.  And here is the final picture.

Voila!  We have finished.  The important thing to learn is how we were able to draw the whole picture by first just sketching out the major parts, and then filling in the details bit by bit.  That’s the idea of top down design, which is a very good way to go about writing computer programs.

# Here’s the “exam” I assigned to the students in my class this week.  It’s due in class next week.  Don’t worry too much about it; the point is more to go back and review before we move on… we’re not failing anyone!

### Instructions

This is what they are working on from now until next week, as a final bit of practice with pictures before we move on to animations.

1. Pick one of the following four pictures.
2. Write a program that draws a simplification of the picture on that page.  Write the program using top-down design, in the way we talked about earlier.
3. As a rule of thumb, divide the overall picture into at least three pieces, and divide each of those into about two to four pieces each.  Part of the assignment is to pick out how to divide the picture into pieces, which details are important and which you can leave out.  Don’t try to draw everything in the picture.
4. Use each of the following at least once in your picture:
• A circle
• A rectangle
• A line or polygon (one or the other is fine)
• Translate, rotate, and scale
• Colors (pick whichever seem best)
• Comments where appropriate to explain what you’re doing.

Remember: The goal isn’t just to get the computer to draw your picture.  It’s also to write a program that is easy to read and understand, looks clean and organized, and explains your picture well.  Be a good communicator.

Okay, so it’s become clear that I am sometimes going to need the weekend to work on writing down what we do in class at length.  So, from now on, I’m going to stop calling this “late” and just say that I’ll plan on getting the blog post done by the end of the weekend.  I’m just changing the definition of “late” so that I’m not late any more.  Very clever, isn’t it?

Until next week, have fun, and feel free to ask questions in the blog comments.

## At long last, I can announce the game interface in gloss-web.  This is still a good ways off in my class, but those of you who know what you’re doing can play around with it anyway.  As always, you can visit

http://dac4.designacourse.com:8000

If you’ve used the site before and don’t see a game button, you may need to hit the refresh button.

## How they work:

Games are similar to simulations, except that the time-step function has one fewer parameter, and there’s an additional event handling function.  So you’ll need to write the following:

`initial :: StdGen -> a`

Just as with simulations, you can pick any data type you like (and probably write your own) to represent the state of the world.  You then define initial to be a function that gets a random number generator, and returns the starting state.  If you need random numbers, you can store the generator in your state type.  The type variable a needs to be the same as a in all the definitions that follow.

`event :: Event -> a -> a`

Here’s how you respond to events: write a function with the event and the previous state of the world, that returns a new state of the world as its result.  That means anything you want to remember about the events that have happened should be part of your world type.

`step :: Float -> a -> a`

Here’s how you respond to the passage of time.  Much like the step function of the simulation interface, the time parameter is the amount of time that’s elapsed since the last step.  Unlike simulations, there is now ViewPort passed in.  That’s because in the OpenGL implementation, simulations automatically provided controls to zoom and such… but games don’t.  So you just get the elapsed time.  (Of course, gloss-web doesn’t provide those automatic transformations anyway.)

`draw :: a -> Picture`

Finally, of course you need to draw the world.  This is where you say what it looks like.

## An Example

The default program is a fairly simple one that draws a ball where ever you place the mouse; not much of a game, really!  Never fear, here’s something a little more involved… and actually pretty fun!  My best score so far is 31.  Can you do better?

```import Graphics.Gloss
import Graphics.Gloss.Interface.Game

data World = World {
player :: Point,
target :: Point,
goal   :: Point,
robot  :: Point,
speed  :: Float,
score  :: Integer
}

initial _ = World (0,0) (0,0) (200,200) (-200,-200) 40 0

event (EventMotion (x,y)) world = world { target = (x,y) }
event _                   world = world

distance (x0, y0) (x1, y1) = sqrt ((x1 - x0)^2 + (y1 - y0)^2)

moveToward (x0,y0) (x1,y1) dist = (x0 + dx, y0 + dy)
where totalDist             = distance (x0,y0) (x1,y1)
dx | dist < totalDist = (x1 - x0) * dist / totalDist
| otherwise        = (x1 - x0)
dy | dist < totalDist = (y1 - y0) * dist / totalDist
| otherwise        = (y1 - y0)

collisions world | distance (player world) (goal  world) < 40 = foundGoal
| distance (player world) (robot world) < 40 = initial
| otherwise                                  = world
where foundGoal = let (x,y) = player world
in  world { goal = (-x, -y), score = score world + 1 }

step time world = collisions newWorld
where
newWorld = world {
player = moveToward (player world) (target world) (time * 60),
robot  = moveToward (robot world)  (player world) (time * speed world),
speed  = speed world + (0.1 * time)
}

draw world = pictures [
color blue  (figure (player world)),
color red   (figure (robot  world)),
color green (figure (goal   world)),
translate (-225) (-225) (scale 0.2 0.2 (text (show (score world))))
]

figure (x,y) = translate x y (circleSolid 20)```

Have fun!

# Where We Are

We’ve gotten a lot done in just two weeks.  To sum up, we’ve done all of these:

• Learned how computer programming works: all about compilers, programming languages, and libraries, and how they work together.
• Wrote computer programs to describe pictures.  We described simple pictures like circles and rectangles.  We modified other pictures by stretching, rotating, and moving them around.  And most importantly, we combined smaller pictures into bigger and more complicated ones.
• Used variables to give names to things in our program, like the individual parts of our pictures… like sun, elephant, and so on.
• Saw for ourselves the importance of staying organized, giving things good names, keeping track of related ideas, and using comments (sections of your program that the compiler ignores) to make notes in your program.

If you like, you can review those ideas in Week 1 and Week 2.  Go on, we’ll wait for you.

# Lines and Polygons

So far, we’ve been spending a lot of time drawing with circles and rectangles.  That’s been fun, but it’s also limiting.  What if you wanted to draw a star?  Maybe you could rig something up by stretching or rotating rectangles in the right ways, but it sure wouldn’t be easy!  We spent our second class last week talking about how to do something more flexible: lines and polygons.

### Cartesian Coordinates

To understand lines and polygons, we’ll need a way to talk about specific places on the drawing.  We do that using something called cartesian coordinates.  The idea is to talk about a point by giving two numbers:

1. How far from the middle of the painting, horizontally.  We call this the x coordinate.
2. Haw far from the middle of the painting, vertically.  We call this the y coordinate.

Here’s a picture that might help (taken from Berkeley Science, here):

We write a point as (x,y) where x and y are the coordinates as above: x goes right or left, and y goes up or down.  The point in the very middle of the picture is called (0,0) because it’s immediately in the center both horizontally and vertically.  Other points can be found by following the x line (or “axis”) to the first coordinate, then moving up or down alongside the y line (the y “axis”) to the second coordinate.  Notice that we use negative numbers to mean “left” or “down”.

Exercise: Take a few minutes to pick some more points on the diagram, and see if you can write down their coordinates — that is, write them as a pair of numbers in parentheses just like the points already labeled.

If you remember, we said earlier that the drawing area on the gloss-web web site is 500 by 500 in size.  That means the center is still (0,0), but the numbers in your coordinates can range from -250 to 250.  (Why?  Because 250 is half of 500, and half of the size is on each side of the center.)  It might help at this point to get out some graph paper, and draw yourself a square, and see if you can find some points… like (100,100) or (-200, 50).  As a special bonus, you can also hover your mouse over the drawing area when you run your programs using gloss-web, and you’ll see a tool tip with the coordinates of the place your mouse pointer is.

### Drawing Lines

Let’s use those coordinates to draw things.  Try out this program:

`import Graphics.Gloss`
`picture = line [ (-100, -100), (-200, 50) ]`

Can you guess at what the result will be?  Now run it, and see for yourself.  It drew a line from one point to the other.  You can also draw longer (jagged) lines by listing even more points.

`import Graphics.Gloss`
```picture = line [
(-200, -200),
( 200, -200),
( 200,  200),
(-200,  200),
(-200, -200)
]```

Try to see where those points will end up on the drawing screen, and then what the result will be.  Now run it.  Did it do what you expected?

### Drawing Polygons

Not only can you draw lines, but you can draw filled-in shapes as well.  These are called polygons, which are just a fancy word for shapes with straight edges as sides.  We can turn the previous example into a filled in shape:

`import Graphics.Gloss`
```picture = polygon [
(-200, -200),
( 200, -200),
( 200,  200),
(-200,  200)
]```

Notice that I didn’t need to repeat the last point like I did for the line.  That’s because shapes have to be closed off, so Gloss assumes that we meant to add a line back to where we started.  Of course, rectangles aren’t very exciting, so here’s a program that Ms. Sue wrote!

```import Graphics.Gloss

picture = stars

stars = pictures [
translate ( 100) ( 100) (color blue   star),
translate (-100) (-100) (color yellow star),
translate (   0) (   0) (color red    star)
]

star = polygon [
(  0,  50),
( 10,  20),
( 40,  20),
( 20,   0),
( 30, -30),
(  0, -10),
(-30, -30),
(-20,   0),
(-40,  20),
(-10,  20),
(  0,  50)
]```

Can you guess what that does?  Here’s the result.

# Thinking Like a Computer

That’s what we did last week.  This week, we’re talking about how to think about computer programs from the computer’s perspective.  We’re going back over everything we’ve learned, but this time we’re pretending to be a computer, reading the programs and trying to interpret them.  Here’s what we’ve talked about so far:

### Modules

When we write our computer programs in the web browser, we type everything into a text box and choose Run.  The whole thing we type into our text box is called a module.  So far, you can think of module as a word that means the entire program.  (We talked a little bit about how programs can have more than one module, too.  In fact, most programs in the world do!  But it will be a while before we’ll really need to separate our programs into more than one module.)

Modules have two kinds of things in them that we’ve seen so far:

• Imports.  These always have to be at the beginning of the module, and they say what other modules (normally from libraries) we’re using.  For example, we always start our programs by importing Graphics.Gloss, because that gives us all the Gloss stuff, like circles and colors and so on.  We normally only import one library, but if you needed to, you could import more than thing.
• Definitions.  A definition tells the computer what a word (called a variable) means.  For example, if you look at the star program earlier, there are three definitions: for the words “picture”, “stars”, and “star”.

An import always starts with the special word “import”.  A definition for a variable always has the name of the variable you’re defining, an equal sign, and the thing you’re defining it to mean.  Sometimes in the past, we’ve seen people try to add other stuff to a module that are not imports or definitions.  For example, maybe you’ve tried to write something like this:

`import Graphics.Gloss`
`circle 80`

If you’ve tried that, you know it doesn’t work!  You can’t throw in a description of the circle just anywhere in your program.  The error you’d get for that would say “Naked expression at top level”.  When you see that, it means you forgot to say what variable you are defining!

### How To Be A Compiler

Here’s what the compiler does: it reads your program, and remembers what words you’ve defined.  Then it know a specific word it wants to look up the meaning of.  For us, that specific word is “picture”.  So it consults your program, and looks up the meaning of “picture”.  Then, if there are any words that occur in there that the compiler doesn’t know, it tries to look those up, too.  As long as there are words it doesn’t know, it keeps looking them up!  Basically, when you write a computer program, you’re giving the compiler a dictionary to look up words in.

With that in mind, think about the next program.

```import Graphics.Gloss

picture = color myFavoriteColor (circle 100)

myFavoriteColor = blue

stars = pictures [
translate ( 100) ( 100) (color blue   star),
translate (-100) (-100) (color yellow star),
translate (   0) (   0) (color red    star)
]

star = polygon [
(  0,  50),
( 10,  20),
( 40,  20),
( 20,   0),
( 30, -30),
(  0, -10),
(-30, -30),
(-20,   0),
(-40,  20),
(-10,  20),
(  0,  50)
]```

If you are a compiler and see this program, what do you do?  Here’s what:

• You see the import, and make a note that this program uses the Gloss library.  You can then go see what’s in the Gloss library, and you’ll see that there are definitions for things like “circle” and “rectangleSolid” and “polygon” and “green”.  You now know what these words mean.
• You then see the definitions in this module.  There are three of them: “picture”, “stars”, and “star”.
• Since your goal in life is to go find out what “picture” means and draw it, you read the definition, and try to understand it.
• Oops, you don’t know what “myFavoriteColor” means!  Not a problem; you go look that up, and find out that it means blue.
• Now you know everything you need about what “picture” means, and you’re done.  You go and draw a blue circle.

You might wonder, what about “stars” and “star”?  Well, you know what they mean… but they never came up.  Just because a word is in the dictionary doesn’t mean you necessarily need it.  Remember, the compiler only uses the parts of your program that it needs to draw the thing you’ve called “picture”.  If you want to see a shape, you need to make it part of the definition of picture (or of some other word that happens in picture, and so on).

### Expressions (and we don’t mean smiles!)

We can talk a little bit more about the things that come after the equal signs in definitions.  These are called expressions, and there are several forms of them we’ve used.  You have seen all of these before, but it will help to review them.

• Variables.  A variable name (something that you’ve defined, or something that comes from a library) can be an expression.  To find out what it means, you’d look up the definition.  Examples of this are picture or green.
• Functions (with arguments).  Another kind of expression we use a lot is a function, along with its arguments (also sometimes called parameters). Examples of this are circle 100, or translate 50 50 star.  Remember that each function expects a certain number of parameters, and you have to give it that many!
• Lists.  A list is a bunch of things in square brackets, separated by commas.  We’ve seen them in two different places now: the parameter to pictures is a list of other pictures.  The parameter to line or polygon is a list of points.
• Points.  A point is a pair of coordinates in parentheses, with a comma between them.  You need them in line and polygon, to go in the list of points you give it.
• Numbers.  A number is written as just itself, like 5 or 1.75.
• Strings.  Remember with text, where we put things in quotes after it?  That’s a form of expression too: a string.

You might have noticed that not all the forms of expressions give you pictures!  Some of them give you numbers, or points, or lists.  It’s up to you to make sure that you’re putting the right type of expression in the right places.  If you try to define picture to be the number 7, for example, it won’t work!  That’s because 7 isn’t a picture… it’s just a number.

Now, here’s where things get interesting: Some of those kinds of expressions have smaller parts… and those smaller parts are expressions too!  So we build up expressions out of other, smaller expressions.

How about an example?  Let’s look at Ms. Sue’s stars program from earlier.  Here it is again, so you don’t have to scroll so far.

```import Graphics.Gloss

picture = stars

stars = pictures [
translate ( 100) ( 100) (color blue   star),
translate (-100) (-100) (color yellow star),
translate (   0) (   0) (color red    star)
]

star = polygon [
(  0,  50),
( 10,  20),
( 40,  20),
( 20,   0),
( 30, -30),
(  0, -10),
(-30, -30),
(-20,   0),
(-40,  20),
(-10,  20),
(  0,  50)
]```

There are three definitions: picture, stars, and star.

The picture definition is easy.  We say that picture means the expression with just one thing in it: the variable stars.  So a picture is the same thing as a stars.  You can define synonyms like this all over the place!  Marcello noticed that you could write:

`move = translate`

And then you don’t have to remember what translate means any more.  (I think you should remember what translate means, though.  Defining a new word for it might help you in the short term to write your program, but it won’t help at all when you need to read someone else’s program!)

Let’s look at star, which is a little bit longer.  The expression used for star is a function with arguments: the function is polygon, and there is one argument.  Remember, that argument is an expression of its own!  In particular, it’s a list, which means it’s a bunch of things separated by commas, surrounded by square brackets.  We can go deeper, though: each of the things in the list is yet another smaller expression: in this case, a point.  And finally, each of the coordinates in a point is yet another expression, which is a number.  So we have expressions within expressions within expressions within expressions!  That’s normally how things go: you do a lot of building up expressions in computer programming.

I’ve been saving the most complicated one for last.  Let’s take a look at stars.  This time, I’ll describe the expression using a bulleted list, and I think you’ll see why.

• At the top level, stars is defined to mean a function with arguments…
• The function is pictures, which is a variable.  So it has no smaller pieces.
• The argument is a list — a bunch of things in square brackets, separated by commas…
• The first thing in the list is a function with arguments…
• The function is translate.  That’s just a variable; it has no smaller parts.
• The first argument is 100.  It’s a number, and has no smaller parts.
• The second argument is also 100, and has no smaller parts.
• The third argument (which means the picture to draw) is another function with arguments.
• The function is color, a variable.
• The first argument is blue, which is a variable.
• The second argument is star, which is also a variable.
• The second thing in the list is a function with arguments…
• The function is translate, a variable.
• The first argument is -100, a number.
• The second argument is -100, a number.
• The third argument is another function with arguments.
• The function is color, a variable.
• The first argument is yellow, a variable.
• The second argument is star, a variable.
• The third thing in the list is yet another function with arguments.
• The function is translate, a variable.
• The first argument is 0, a number.
• The second argument is 0, a number.
• The third argument is another function with arguments.
• The function is color, a variable.
• The first argument is red, a variable.
• The second argument is star, a variable.

That was long!  But can you look over it, and see how we can break down the expression into pieces, and each of their pieces is another expression?

# Understanding Programs

The last thing we did this week, and also your homework, was to try to predict the results of some programs.  Here’s how this works.

1. You’ll need some graph paper — you know, the kind with little squares all over it.
2. Draw a square on your graph paper… maybe make it 10 boxes to a side.
3. Draw a dot right exactly in the middle of your square.  This is the point (0,0).

If you made your square 10 boxes to a side, then each box is a distance of 50.  See if you can find some points in your square.

• Find the point (250, 250).
• (You should have come up with the top right corner of the box.)
• Find the point (0, -250).
• (You should come up with the point in the middle of the bottom edge.)

Now your goal will be to read some programs, and try to draw what they would draw.  You can check your answers using the programming environment.  Be careful, though.  If you submit one of these programs, your computer will forget the program you’ve been working on, so be sure to save a copy of that somewhere first!

### Exercise 1: Draw the following.

```import Graphics.Gloss
picture = rotate 45 (rectangleWire 150 150)```

### Exercise 2: Draw the following.

```import Graphics.Gloss
picture = rotate 135 (pictures [
circle 50,
rectangleWire 10 100
])```

### Exercise 3: Draw the following.

```import Graphics.Gloss
picture = translate 50 0 (rotate 45 triangle)
triangle = line [ (0,0), (100,200), (-100,200), (0,0) ]```

### Exercise 4: Draw the following.

```import Graphics.Gloss
picture = rotate 90 (translate 100 0 (circle 100))```

After you’ve tried those, try making up some expressions of your own, and predict what they are going to do.  We’re spending some time on this, because before we can move on to animations, it’s important to see what your programs mean!

That’s all until next week.