01: package kawa.lang;
02:
03: import gnu.mapping.*;
04: import gnu.text.Printable;
05: import gnu.lists.Consumer;
06:
07: /** Implement Scheme "promises".
08: * @author Per Bothner
09: */
10:
11: public class Promise implements Printable {
12: Procedure thunk;
13:
14: /** The result - or null if it is not ready. */
15: Object result;
16:
17: /** Create a new Promise that will evaluate thunk when forced. */
18: public Promise(Procedure thunk) {
19: this .thunk = thunk;
20: }
21:
22: public Object force() throws Throwable {
23: if (result == null) {
24: Object x = thunk.apply0();
25: if (result == null)
26: result = x;
27: }
28: return result;
29: }
30:
31: public void print(Consumer out) {
32: if (result == null)
33: out.write("#<promise - not forced yet>");
34: else {
35: out.write("#<promise - forced to a ");
36: out.write(result.getClass().getName());
37: out.write('>');
38: }
39: }
40: }
|