raz / conform / run / Sorted.raz

51 lines · 1.6 KiB · raw · history · last change 264716cb

1(* A generic sort: slices in many orders and of every length up to 40 come out
2 in order, holding what they held; and a sort by a record's field. *)
3module Sorted;
4import Out, Rt, Ints := Order(I64, below), ByAge := Order(Person, younger);
5
6type Person = record name: []const U8; age: I64; end;
7
8proc below(a, b: I64): BOOL;
9begin
10 return a < b;
11end;
12
13proc younger(a, b: Person): BOOL;
14begin
15 return a.age < b.age;
16end;
17
18proc main*;
19var
20 a: [40]I64; count: [10]I64; n, i, kind, seed: I64;
21 people: [4]Person;
22begin
23 seed := 7;
24 for n := 0 to 40 do
25 for kind := 0 to 3 do
26 for i := 0 to 9 do count[i] := 0; end;
27 for i := 0 to n - 1 do
28 seed := (seed * 1103515245 + 12345) & 7FFFFFFFH;
29 if kind = 0 then a[i] := seed mod 10; (* at random, with repeats *)
30 elsif kind = 1 then a[i] := i mod 10; (* rising *)
31 elsif kind = 2 then a[i] := 9 - i mod 10; (* falling *)
32 else a[i] := 5; (* all equal *)
33 end;
34 INC(count[a[i]]);
35 end;
36 Ints.sort(a[0..n]);
37 for i := 0 to n - 1 do
38 if (i > 0) and (a[i - 1] > a[i]) then Rt.stop("out of order"); end;
39 DEC(count[a[i]]);
40 end;
41 for i := 0 to 9 do
42 if count[i] # 0 then Rt.stop("not what it held"); end;
43 end;
44 end;
45 end;
46 people := [{name: "Ana", age: 41}, {name: "Bo", age: 7}, {name: "Cy", age: 90}, {name: "Di", age: 23}];
47 ByAge.sort(people);
48 for i := 0 to 3 do Out.str(people[i].name); Out.char(' '); Out.int(people[i].age); Out.ln; end;
49end;
50
51end Sorted.