awa.p 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. { $Id$ }
  2. program ArrayWithoutArray(input, output);
  3. { We simulate a (read-only) array by constructing a mapping
  4. function map(n) which yields the n-th element.
  5. We demonstrate its existence by first printing the length
  6. of the array and then its contents.
  7. This technique was first introduced by F.E.J. Kruseman-Aretz,
  8. in the early sixties.
  9. }
  10. procedure Action(n: integer; function map(n: integer): integer);
  11. { Action is called when the construction of the virtual
  12. array is finished. Actually, all elements now reside
  13. on the stack.
  14. n: the length of the array,
  15. map: the mapping function.
  16. }
  17. var i: integer;
  18. begin { show that the whole array is still there }
  19. writeln('#elems:', n);
  20. write('elems:');
  21. for i:= 1 to n do
  22. write(map(i))
  23. end {Action};
  24. procedure Construct(n: integer; function oldmap(n: integer): integer);
  25. { For each value read, Construct will store that value and
  26. declare a new map function, composed of the old one
  27. augmented by the new value.
  28. It then calls itself recursively for the next value.
  29. n: element number on this level
  30. oldmap: map for 1 .. n-1
  31. }
  32. var x: integer; { the value stored at level n }
  33. function newmap(i: integer): integer;
  34. { yields elements stored so far }
  35. begin
  36. if { the i-th element is kept on this level}
  37. i = n
  38. then { yield it }
  39. newmap := x
  40. else { try lower down the road }
  41. newmap := oldmap(i)
  42. end {newmap};
  43. begin
  44. read(x);
  45. if { it is a valid value }
  46. x >= 0
  47. then { we continue reading values and constructing maps }
  48. Construct(n + 1, newmap)
  49. else { we stop reading and pass the info on to Action }
  50. Action(n - 1, newmap)
  51. end {Construct};
  52. function EmptyMap(n: integer): integer;
  53. begin
  54. writeln('Illegal index', n, '; 0 yielded.');
  55. EmptyMap := 0
  56. end {EmptyMap};
  57. begin
  58. Construct(1, EmptyMap)
  59. end.