Skip to content
February 14, 2012 / cdsmith

Juggling in Haskell and Gloss

Just sharing what we’ve been talking about in my classes at LSV (Little School on Vermijo) the past few days.  It all started when a math teacher I follow on Google+ posted a link to this video on the mathematics of juggling, by Cornell professor Allen Knutson.

So we all watched the video, and talked about it… and then about midnight last night, I realized this would make a perfect introduction to Gloss simulations, which we’re learning about in our Haskell programming class!  Fast forward about 20 minutes of hacking, and we have this short program:

import Graphics.Gloss
thePattern = [5,2,5,1,2]
initial g = (-1, 0.0, [], cycle thePattern)
step dt (hand, time, balls, pattern) = (newhand, newtime, newballs, newpattern)
    where (throw, newtime) = properFraction (time + dt)
          newhand    = if throw == 1 then -hand else hand
          thrown     = if throw == 1 then [ (hand, newtime, head pattern) ]
                                     else []
          newpattern = if throw == 1 then tail pattern else pattern
          newballs   = [ (bhand, btime + dt, height)
                       | (bhand, btime, height) <- balls,
                         btime + dt < fromIntegral height ]
                       ++ thrown
draw (hand, time, balls, pattern) = pictures [
    pictures [ ball b | b <- balls ]
ball (bhand, btime, height) = translate (50*x) (50*y) (circleSolid 10)
    where t = 1 - 2 * (btime / fromIntegral height)
          x = if even height then bhand else bhand * t
          y = if height < 3 then 0 else fromIntegral (height - 1) * (1 - t^2)
juggler = pictures [
    line [(-50, 0), (0, 25), (50, 0)],
    line [(-30, -100), (0, -50), (30, -100)],
    line [( 0, 25), (0, -50)],
    translate 0 50 (circle 25)

Feel free to check it out.

This isn’t the best code in the world, because I deliberately write it to avoid as many ideas as I can that we haven’t talked about in my Haskell class.  Among those, for example, are any kind of user-defined data types, or any structured data other than tuples and lists!  I’ve also used list comprehensions when maps and filters might be clearer, for the same reason: we’ve done list comprehensions in class!  Those are coming soon, but for the time being, it’s not too hard to see what’s going on here.  A couple notes about the world type:

  • The state of world comprises four pieces of information: which hand will throw next, how much time has passed since the last throw, what balls are in the air, and what pattern is coming up next.  Since we don’t have user-defined types and it makes the math easy, I’ve described hands as -1 for left, and +1 for right.
  • The balls in the air form a list, but each element of that list is another tuple, containing the hand the ball was thrown from, how long it has been in the air, and its height.

So like all Gloss simulations, we need to specify three things:

  1. The initial state.  This is the left hand, no time since the last throw, no balls in the air, and the pattern sitting ahead of us.  The cycle function turns a finite list into an infinite repeating one.
  2. The step function.  This is where most of the logic sits… there are a lot of bits, but it does what you’d expect!  Every second, a ball is thrown, and the hand switches sides.  We update the balls to add to their time in the air, and keep only the ones that haven’t landed.  When a ball is thrown, we add it.  And each time we drop a number from the pattern.
  3. The draw function.  This draws the juggler and all of the balls.  The balls are drawn with some faux-physicsy thing that, frankly, is just the result of fiddling and isn’t an accurate physics simulation.  I can get away with that when teaching middle schoolers!  Hey, at least they follow parabolas; just not all with the same acceleration.  In class I just skimmed over the math for where the ball appears, since the class right now is about the state type, and drawing is something they’ve been doing all year anyway.

Definitely a lot of fun.  I encourage you to copy and paste the code above into and fiddle with the patterns and see what they look like!

October 10, 2011 / cdsmith

Build Your Own Simple Random Numbers

Liam O’Connor got me thinking about the best way to explain the idea of a pseudo-random number generator to new programmers.  This post is my answer.  If you already understand them, there won’t be anything terribly new here.  That said, I enjoy clean examples even for easy ideas, so if you do too, then read on!

Note: The title may have caused some confusion.  I’m not suggesting you use the trivial algorithms provided here for any purpose.  Indeed, they are intentionally over-simplified to make them more understandable.  You should read this as an explanation of the idea of how generating random numbers works, and then use the random number generators offered by your operating system or your programming language, which are far better than what’s provided here.

The Problem

Suppose you’re writing a puzzle game, and you need to choose a correct answer.  Or suppose you are writing a role-playing game, and need to decide if the knight’s attack hits the dragon or deflects off of its scales.  Or you’re writing a tetris game, and you need to decide what shape is going to come next.  In all three of these situations, what you really want is a random number.  Random numbers aren’t the result of any formula or calculation; they are completely up to chance.

Well, here’s the sad truth of the matter: computers can’t do that.  Yes, that’s right.  Picking random numbers is one of those tasks that confound even the most powerful of computers.  Why?  Because computers are calculating machines, and we just said that random numbers aren’t the result of any calculation!

Of course, you’ve probably played games on a computer before that seem to pick numbers at random, so you may not believe me.  What you’re seeing, though, aren’t really random numbers at all, but rather pseudo-random numbers.  Pseudo-random numbers are actually the result of a mathematical formula, but one designed to be so complicated that it would be hard to recognize any pattern in its results!

Writing a Pseudo Random Number Generator

A lot of smart people actually spend a lot of time on good ways to pick pseudo-random numbers.  They try a bunch of different complicated formulas, and try to make sure that patterns don’t pop up.  But we can build a simple one pretty easily to pick pseudo-random numbers from 1 to 10.  Here it is, in the programming language Haskell:

random i = 7 * i `mod` 11

Since it’s a function, it needs to have an input.  It then multiplies that input by 7, and then finds the remainder when dividing by 11.  We’ll give it the previous number it picked as input, and it will give us back the next one.  Suppose we start at 1.  Then we get the following:

random  1 ->  7
random  7 ->  5
random  5 ->  2
random  2 ->  3
random  3 -> 10
random 10 ->  4
random  4 ->  6
random  6 ->  9
random  9 ->  8
random  8 ->  1

Let’s look at the range of answers.  Since the answer is always a remainder when dividing by 11, it’ll be somewhere between 0 and 10.  But it should be pretty easy to convince ourselves that if the number we give as input is between 1 and 10, then 0 isn’t a possibile answer: if it were, then we’d have found two numbers, both less than 11, that multiply together to give us a multiple of 11.  That’s impossible because…. 11 is prime.  So we’re guaranteed that this process picks numbers between 1 and 10.  It seems to pick them in a non-obvious order with no really obvious patterns, so that’s good.  We appear to have at least a good start on generating random numbers.

Notice a couple things:

  • We had to pick somewhere to start.  In this case, we started out by giving an input of 1.  That’s called the seed.  If you use the same seed, you’ll always get the exact same numbers back!  Why?  Because it’s really just a complicated math problem, so if you do the same calculation with the same numbers, you’ll get the same result.
  • To get the next number, we have to remember something (in our case, the last answer) from the previous time.  That’s called the state.  The state is important, because it’s what makes the process give you different answers each time!  If you didn’t remember something from the last time around, then you’d again be doing the same math problem with the same numbers, so you’d get the same answer.

Doing Better By Separating State

Unfortunately, our random number generator has a weakness: you can always predict what’s coming next, based on what came before.  If you write tetris using the random number generator from earlier, your player will soon discover that after a line, they always get an L shape, and so on.  What you really want is for your game to occasionally send them a line followed by a T, or even pick two lines in a row from time to time!

How do we do this?  Well, the next answer that’s coming depends on the state, so our mistake before was to use the previous answer as the state.  The solution is to use a state that’s bigger than the answer.   We’ll still be looking for random numbers from 1 to 10, but let’s modify the previous random number generator to remember a bigger state.  Now, since state and answer are different things, our random function will have two results: a new state, and an answer for this number.

random i = (j, ans)
    where j   = 7 * i  `mod` 101
          ans = (j - 1) `mod` 10 + 1  -- just the ones place, but 0 means 10

That says take the input, multiply by 7, and find the remainder mod 101.  Since 101 is still prime, this will always give answers from 1 to 100.  But what we really wanted was a number from 1 to 10, just like the one we had before.  That’s fine: we’ll just take the ones place (which is between 0 and 9) and treat 0 as 10.  The tens place doesn’t really change the answer at all, but we keep it around to pass back in the next time as state.

Let’s see how this works:

random  1 -> ( 7,  7)
random  7 -> (49,  9)
random 49 -> (40, 10)
random 40 -> (78,  8)
random 78 -> (41,  1)
random 41 -> (85,  5)
random 85 -> (90, 10)
random 90 -> (24,  4)
random 24 -> (67,  7)
random 67 -> (65,  5)
random 65 -> (51,  1)

Excellent!  Now instead of going in a fixed rotation, some numbers are picked several times, and some haven’t been picked yet at all (but they will be, if we keep going), and you can no longer guess what’s coming next just based on the last number you saw.  In this random number generator, the seed was still 1, and the state was a number from 1 to 100.

People who are really interested in good random numbers sometimes talk about the period of a pseudo-random number generator.  The period is how many numbers it picks before it starts over again and gives you back the same sequence.  Our first try had a period of 10, which is rather poor.  Our second try did much better: the period was 100.  That’s still pretty far off, though, from the random number generators in most computers, the period of which can be in the millions or billions.

Real World Pseudo-Random Number Generators

Our two toy pseudo-random number generators were fun, but you wouldn’t use them in real programs.  That’s because operating systems and programming languages already have plenty of ways to generate pseudo-random numbers.  And those were created by people who probably have more time to think about random numbers than you do!  But some of the same ideas come up there.  For example, consider this (specialized) type signature for the random function in the Haskell programming language:

random :: StdGen -> (Int, StdGen)

Look familiar?  StdGen is the state, and choosing a random Int gives you back the Int, and a new StdGen that you can use to get more pseudo-random numbers!  Many programming languages, including Haskell, also have “global” random number generators that remember their state automatically (in Haskell, that is called randomIO), but under the covers, it all comes down to functions like the ones we’ve written here… except a lot more complex.

Where To Get a Seed

We’ve still left one question unanswered: where does the seed come from?  So far, we’ve always been using 1 for the seed, but that means that each time the program runs, it will get the same numbers back.  So we end up with a similar situation to what we saw before, where players will realize that a game starts with the same sequence of random events each time.

To solve this problem, the seed should come from somewhere that won’t be the same each time.  Here are two different ways to seed a random number generator.

  1. Mostly, pseudo-random number generators are seeded from a clock.  Imagine if you looked at the second hand on a clock, used it to get a number from 1 to 60, and used that for your seed.  Then the game would only act the same if it started at the same number of seconds.  Even better, you could take the number of seconds since some fixed time in the past, so you’d get an even bigger difference in seeds.  (Entirely by coincidence, computers often use the number of seconds since January 1, 1970.)
  2. You might try to get a good seed from details of the way the user uses your program.  For example, you can look at the exact place the user first clicks the mouse, or exactly how much time passes between pressing keys.  They will most likely not be exact, and click a few pixels off or type ever so slightly slower, even if they are trying to do exactly the same thing.  So, again, you get a program that acts differently each time.  This is called using entropy.

Most of the time, using the computer’s built-in clock is okay.  But suppose you’re making up a code word.  It would be very bad if someone could guess your code word just by knowing when you picked it!  (They would also need to know how your computer or programming language picks random numbers, but that’s not normally kept secret; they can probably find that out pretty easily.)  Computer security and privacy often depends on picking unpredictable random numbers — ones that people snooping on you won’t be able to guess.  In that case, it’s important that you use some kind of entropy, and not just the clock.  In fact, when security is at stake, you can use entropy to modify the state as well, to make sure things don’t get too predictable.  Most operating systems have special ways of getting “secure” random numbers that handle this for you.

Another example of entropy:

If you play the game Dragon Warrior for the Nintendo, but use an emulator instead of a real Nintendo, then you can save a snapshot of your game before you fight a monster, memorize what the monsters are going to do, and figure out exactly the right way to respond.  When you load the game from the snapshot and try again, as long as you do the same things, the monster will respond in exactly the same way!  That’s because the snapshot saves the state of the random number generator, so when you go back and load from the snapshot, the computer picks the same random numbers.  So if a fight against a monster is going well but you make a disastrous move at the end, you can load your snapshot and repeat the exact same fight up to that point.

The same trick doesn’t work in Dragon Warrior 2 (or later ones), though!  Why not?  Because the company that makes the game started using entropy in their sequel.  So now little things like exactly how long you wait between pressing buttons will change the game.  Since you can’t possibly time everything exactly the same down to hundredths or thousandths of a second, the task is hopeless, and you have to just take your chances and trust to luck.

So as you can see, random numbers can become a very tricky topic.  But ultimately it’s all just a complicated formula, a seed, and a state.

October 9, 2011 / cdsmith

Just for fun: Hangman with gloss-web

So this will be brief.  Ivan Miljenovic pointed me to a discussion about writing games with kids, and the question came up about how clearly one could write a hangman game.  To I took that a challenge, and I present to you: Hangman in gloss-web!

Edit: I’ve now added a random number generator to the signature of the initial worlds, so it even chooses words at random.

The code:

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

import System.Random

import Data.Char

possibleWords = [
    "cat", "hat", "zebra", "delicious", "water",
    "elephant", "granite", "sunset", "dragon"

data World = World {
    word    :: String,
    strikes :: Int,
    guesses :: [Char]

initial g = World (possibleWords !! i) 0 []
  where (i, _) = randomR (0, length possibleWords - 1) g

lost world = strikes world == 6
won  world = all (`elem` guesses world) (word world)
over world = won world || lost world

event (EventKey (Char c) Down _ _) world
  | not (isLetter c)                     = world
  | over world                           = world
  | toLower c `elem` guesses world       = world
  | toLower c `elem` word world          = world { guesses = c : guesses world }
  | otherwise                            = world { strikes = strikes world + 1,
                                                   guesses = c : guesses world }
event _                            world = world

step time world = world

draw world = pictures [ frame, hangee world, answer world ]

frame = pictures [
    line [ (100, -50), (-100, -50), (-100, 200), (0, 200), (0, 150) ],
    line [ (-75, -50), (-100, -25) ]

hangee world = pictures (take (strikes world) parts)
  where parts = [ hangeeHead, hangeeBody, leftArm, rightArm, leftLeg, rightLeg ]

hangeeHead = translate 0 125 (circle 25)
hangeeBody = line [ (0, 100), (  0, 30) ]
leftArm    = line [ (0,  90), (-30, 60) ]
rightArm   = line [ (0,  90), ( 30, 60) ]
leftLeg    = line [ (0,  30), (-30,  0) ]
rightLeg   = line [ (0,  30), ( 30,  0) ]

answer world = translate (-50) (-200)
             $ scale 0.3 0.3
             $ color (wordColor world)
             $ text (letters world)

wordColor world
  | won  world = dark green
  | lost world = red
  | otherwise  = black

letters world = concat [
    if c `elem` guesses world then [c, ' '] else "_ "
      | c <- word world
And, here's what it looks like:

To run the code, visit, choose Game, and copy and paste the code above into the editor area.  Or visit this link to just play the game.  Have fun!

October 6, 2011 / cdsmith

Haskell For Kids: Week 8

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.


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.


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:

See how graphs of functions help you understand what they do?

Your Task

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.

September 28, 2011 / cdsmith

Haskell for Kids: Week 7

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, 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 [
    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.

September 27, 2011 / cdsmith

Haskell For Kids: Week 6

(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.


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…

September 14, 2011 / cdsmith

Haskell for Kids: Week 5

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:

  1. First Week: The Basics
  2. Second Week: Organization
  3. Third Week: Playing Computer
  4. Fourth Week: Top Down Design

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)


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

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!


  • 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.