TopFor loopsLists

Lists

Sometimes we have a lot of very similar data, and we would like to do similar things to each datum. For example, last week we looked at a program in which we had a bunch of balls, each of which moved a bit to simulate a chain reaction.

In mathematics this is done by attaching subscripts to names. We can talk about numbers n1, n2,... We want to be able to do the same thing with computer languages. The name for this type of group of elements in Grace is a list.

Suppose we wish to have a group of elements all of which have type ThingAMaJig and we wish to call the group things. Then we write the declaration of things as

    def thing: List<ThingAMaJig> = list.with<ThingAMaJig>(...)

We can now refer to individual elements by their number in the list

    thing.at(1), thing.at(2), ..., thing.at(25)

We start numbering at 1.

We can also add elements to a list one at a time.

     def name: List<String> = list.empty<String>
 

The program Slides, provides a slide show.

In this code we declare a list of Graphic2D, where the actual elements are drawable images:

  def slide: List<Graphic2D> = list.empty
  def bruce: Graphic2D = drawableImage.at(startPosn) size (125, 125)
          url ("http://www.cs.pomona.edu/classes/cs051G/Images/kbruce.png")
          on (canvas)
  slide.add(bruce)

Each time we add an item, we add it to the end of the list.

We included buttons that allow the user to walk through the slide show in order, either forward or backward.

There are two buttons available named next and previous. Clicking on either calls the method changeSlide with a parameter indicating whether we are counting up or down:

  method changeSlide(isNext: Boolean) -> Done {
    slide.at(slideNumber).visible := false
    if (isNext) then {
      slideNumber := (slideNumber % numSlides) + 1
    } else {
      slideNumber := if (slideNumber == 1) 
                then {numSlides} 
                else {slideNumber - 1}
    }
    slide.at(slideNumber).visible := true
  }

Notice how easy it is to move from one element to the next with a list. Make sure you understand why if isNext is true then we move successively forward through the slides. After the last is obtained, we go back to the first. If isNext is false, we go through the slides backwards.


TopFor loopsLists