tags:

views:

105

answers:

2

Hi, below is a program in a statically-scoped language:

program main
   int x, y;
   void p1(value int y, void q(reference int)) {
      void p2(reference int x) {
            x := y + 2;
            print(x);
            q(y);
            }
      if x = y then q(y) else p1(y+1, p2)
      }
   void p2(reference int x) {
        x := y + 2;
        print(x);
        }
   x := 2;
   y := x;
   p1(0, p2);
end main

by "value" it means parameter transmitted by value, "reference" by reference.

Will function call "q(y)" in p2 cause infinite loop?

A: 

It prints 4. In Java:

import java.util.concurrent.atomic.AtomicInteger;

public class Test {

    public static void main(String... a) {
        new Test().run();
    }

    AtomicInteger x = new AtomicInteger(0);
    AtomicInteger y = new AtomicInteger(0);

    void run() {
        x.set(2);
        y.set(x.get());
        new P1().p1(new AtomicInteger(0), new P2());
    }

    interface Q {
        void q(AtomicInteger x);
    }

    class P2 implements Q {
        public void q(AtomicInteger x) {
            x.set(y.get() + 2);
            System.out.println(x.get());
         }
    }

    class P1 implements Q {
        public void q(AtomicInteger x) {
            x.set(y.get() + 2);
            System.out.println(x.get());
         }
        void p1(AtomicInteger y, Q q) {
            if (x.get() == y.get()) {
                q.q(y);
            } else {
                p1(new AtomicInteger(y.get()+1), this);
            }
        }
    }

}
Thomas Mueller
The line `x.set(y.get() + 2);` uses the instance variable `y`, but in the OP question, it uses the `y` declared in `p1`.
imgx64
Yes. There are probably some errors. I will not try to fix them however, so at least this much is left to the student :-)
Thomas Mueller
A: 

Since it's statically-scoped, you can change the variable names inside functions to avoid the confusion intended by the question. I'm replacing y in p1 with p1y, p2 in p1 with p1p2, x in p1p2 with p1p2x and x in p2 with p2x (it looks even uglier now, though). I also slightly changed the formatting.

program main
  int x, y;
  void p1(value int p1y, void q(reference int)) {
    void p1p2(reference int p1p2x) {
      p1p2x := p1y + 2;
      print(p1p2x);
      q(p1y);
    }

    if x = p1y then {
      q(p1y);
    } else {
      p1(p1y+1, p1p2);
    }
  }

  void p2(reference int p2x) {
    p2x := y + 2;
    print(p2x);
  }

  x := 2;
  y := x;
  p1(0, p2);
end main

Since this is homework, you should be able to take it from here easily, using whatever methods they taught you (follow the execution line by line, draw a stack, etc). But the final answer is yes, it will loop infinitely, printing 4 6 8 and so on.

imgx64