7.4.2 C:   Loops
On this page:
7.4.2.1 Python
7.4.2.2 Java
7.4.2.3 Racket
7.4.2.4 Task
7.4.2.5 Submission
7.4.2 C: 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:

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

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

7.4.2.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();

        }

    }

}

7.4.2.3 Racket
(define button-list
  (for/list ([i (in-range 0 10)])
    (lambda () (display i))))
 
(for ([button button-list])
  (button))
7.4.2.4 Task

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

Run these programs in Python, Java, and Racket (#lang racket) respectively, and see what output they produce.

Explain what might be going on behind the scenes that causes these differences.

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.

7.4.2.5 Submission

Form