showcase20.mod 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. MODULE Showcase20;
  2. // Session showcase: array and record constructors (GNU Modula-2).
  3. //
  4. // * a CHAR-array CONST from a constructor;
  5. // * a CARDINAL-array CONST using the `expr BY n` repeat form;
  6. // * a static record constructor (a nested array-from-string field
  7. // and an inlined nested record field);
  8. // * a runtime record constructor (fields from variables);
  9. // * a runtime array constructor (elements from variables).
  10. //
  11. // Expected ExitCode: 42.
  12. IMPORT TextIO, Conversions;
  13. TYPE
  14. Name = ARRAY [0..7] OF CHAR;
  15. Triple = ARRAY [0..2] OF CARDINAL;
  16. Date = RECORD y, m, d : CARDINAL END;
  17. Person = RECORD name : Name; born : Date END;
  18. CONST
  19. Greet = Name { 'H','e','l','l','o','!','!','!' };
  20. Base = Triple { 7, 7 BY 2 }; (* the repeat form: 7, 7, 7 *)
  21. VAR
  22. p, q : Person;
  23. a, b : Triple;
  24. i : CARDINAL;
  25. total : CARDINAL;
  26. msg : ARRAY [0 .. 63] OF CHAR;
  27. num : ARRAY [0 .. 15] OF CHAR;
  28. ExitCode : INTEGER;
  29. BEGIN
  30. (* static record constructor: string field + inlined nested record *)
  31. p := Person { "Modula", Date { 1980, 5, 3 } };
  32. (* runtime record constructor: every field is a runtime value *)
  33. i := p.born.m; (* 5 *)
  34. q := Person { "Runtime", Date { i, i + 1, i + 2 } };
  35. (* runtime array constructor: elements from variables *)
  36. a := Triple { i, i + 1, i + 2 }; (* 5, 6, 7 *)
  37. b := Triple { Base[0], Base[1], Base[2] };
  38. total := 0;
  39. total := total + Base[0] + Base[1] + Base[2]; (* 7+7+7 = 21 *)
  40. total := total + a[0] + a[1] + a[2]; (* 5+6+7 = 18 *)
  41. total := total + p.born.d; (* 3 = 42 *)
  42. Conversions.CardToStr(total, num);
  43. msg := "showcase20 total=" + num;
  44. TextIO.WriteString(msg);
  45. TextIO.WriteLn;
  46. IF (total = 42)
  47. AND (Greet[0] = 'H') AND (Greet[7] = '!')
  48. AND (p.name[0] = 'M') AND (p.born.y = 1980)
  49. AND (q.name[0] = 'R') AND (q.born.d = 7)
  50. AND (b[0] = 7) AND (b[2] = 7)
  51. THEN ExitCode := 42 ELSE ExitCode := 1 END
  52. END Showcase20.