Loops
On this page:
1.1 Python
1.2 Java
1.3 Racket
1.4 Task
1 Loops

Imagine you are asked to write a program that implements a calculator. The core of this program is a panel of buttons corresponding to the digits 0 through 9. Each button, when pressed, should emit the corresponding digit (we ignore the rest of the interface and implementation for this assignment).

Consider the following pseudocode, which represents this idea:

create initial button_list

 

for i from 0 through 9:

  set button_list[i] to

    lambda: print i

 

# now simulate pushing the buttons

# which means invoking the stored callbacks

 

for i from 0 through 9:

  button_list[i]()

 

# this should print 0 through 9

Here are three natural transcriptions of this program. Some of these programs may produce errors or other surprising output. Before you ask: There are no typos in the following programs. Each has been carefully checked. They are behaving as we expect.

1.1 Python

Make sure you run this in Python 3.

button_list = []

 

for i in range(10):

    button = lambda: print(i)

    button_list.append(button)

 

for button in button_list:

    button()

1.2 Java

Make sure you run this in Java 1.8 or newer, and put this in a file called Buttons.java.

import java.util.*;

 

public class Buttons {

 

    public static interface Button {

        void press();

    }

 

    public static void main(String[] args) {

 

        List<Button>buttonList = new LinkedList<>();

 

        for(int i = 0; i < 10; i++) {

            // Uses Java8's new lambda syntax

            Button b = () -> System.out.println(i);

            b.press();

            buttonList.add(b);

        }

 

        for(Button b : buttonList) {

            b.press();

        }

    }

}

1.3 Racket

#lang racket

 

(define button-list

  (for/list ([i (in-range 0 10)])

    (lambda () (println i))))

 

(for ([button button-list])

  (button))

1.4 Task

Confirm that these programs look essentially equivalent, so they should all work essentially the same way.

Run these programs in Python, Java, and Racket respectively, and see what output they produce. For simplicity, you can run these programs directly on the Web:
What happens?

You aren’t expected to already know what is going on! You may search in general terms on sites like StackOverflow, just as you would as a programmer. You may not, however, ask about this code. You also must not search for terms specifically related to this assignment. Try your best to explain what might be going on behind the scenes that causes these differences.