1 { $Id: awa.p,v 1.2 1994/06/24 10:50:41 ceriel Exp $ }
3 program ArrayWithoutArray(input, output);
4 { We simulate a (read-only) array by constructing a mapping
5 function map(n) which yields the n-th element.
6 We demonstrate its existence by first printing the length
7 of the array and then its contents.
8 This technique was first introduced by F.E.J. Kruseman-Aretz,
12 procedure Action(n: integer; function map(n: integer): integer);
13 { Action is called when the construction of the virtual
14 array is finished. Actually, all elements now reside
16 n: the length of the array,
17 map: the mapping function.
20 begin { show that the whole array is still there }
21 writeln('#elems:', n);
27 procedure Construct(n: integer; function oldmap(n: integer): integer);
28 { For each value read, Construct will store that value and
29 declare a new map function, composed of the old one
30 augmented by the new value.
31 It then calls itself recursively for the next value.
33 n: element number on this level
34 oldmap: map for 1 .. n-1
36 var x: integer; { the value stored at level n }
38 function newmap(i: integer): integer;
39 { yields elements stored so far }
41 if { the i-th element is kept on this level}
45 else { try lower down the road }
51 if { it is a valid value }
53 then { we continue reading values and constructing maps }
54 Construct(n + 1, newmap)
55 else { we stop reading and pass the info on to Action }
59 function EmptyMap(n: integer): integer;
61 writeln('Illegal index', n, '; 0 yielded.');
66 Construct(1, EmptyMap)