comparison ppc/test/cpsfac.p @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:bfdcc3820b32
1 (* cpsfac.p *)
2
3 proc fac(n: integer; proc k(r: integer): integer): integer;
4 proc k1(r: integer): integer;
5 var r1: integer;
6 begin
7 r1 := n * r;
8 print_num(n); print_string(" * "); print_num(r);
9 print_string(" = "); print_num(r1); newline();
10 return k(r1)
11 end;
12 begin
13 if n = 0 then return k(1) else return fac(n-1, k1) end
14 end;
15
16 proc id(r: integer): integer;
17 begin
18 return r
19 end;
20
21 begin
22 print_num(fac(10, id));
23 newline()
24 end.
25
26 (*<<
27 1 * 1 = 1
28 2 * 1 = 2
29 3 * 2 = 6
30 4 * 6 = 24
31 5 * 24 = 120
32 6 * 120 = 720
33 7 * 720 = 5040
34 8 * 5040 = 40320
35 9 * 40320 = 362880
36 10 * 362880 = 3628800
37 3628800
38 >>*)
39
40 (*[[
41 MODULE Main 0 0
42 IMPORT Lib 0
43 ENDHDR
44
45 PROC _fac 0 0 0
46 ! if n = 0 then return k(1) else return fac(n-1, k1) end
47 LDLW 16
48 JEQZ L3
49 JUMP L4
50 LABEL L3
51 CONST 1
52 LDLW 24
53 LDLW 20
54 PCALLW 1
55 RETURNW
56 LABEL L4
57 LOCAL 0
58 GLOBAL _k1
59 LDLW 16
60 CONST 1
61 MINUS
62 CONST 0
63 GLOBAL _fac
64 PCALLW 3
65 RETURNW
66 END
67
68 PROC _k1 4 0 0
69 ! r1 := n * r;
70 LDLW 12
71 LDNW 16
72 LDLW 16
73 TIMES
74 STLW -4
75 ! print_num(n); print_string(" * "); print_num(r);
76 LDLW 12
77 LDNW 16
78 CONST 0
79 GLOBAL lib.print_num
80 PCALL 1
81 CONST 3
82 GLOBAL g1
83 CONST 0
84 GLOBAL lib.print_string
85 PCALL 2
86 LDLW 16
87 CONST 0
88 GLOBAL lib.print_num
89 PCALL 1
90 ! print_string(" = "); print_num(r1); newline();
91 CONST 3
92 GLOBAL g2
93 CONST 0
94 GLOBAL lib.print_string
95 PCALL 2
96 LDLW -4
97 CONST 0
98 GLOBAL lib.print_num
99 PCALL 1
100 CONST 0
101 GLOBAL lib.newline
102 PCALL 0
103 ! return k(r1)
104 LDLW -4
105 LDLW 12
106 LDNW 24
107 LDLW 12
108 LDNW 20
109 PCALLW 1
110 RETURNW
111 END
112
113 PROC _id 0 0 0
114 ! return r
115 LDLW 16
116 RETURNW
117 END
118
119 PROC MAIN 0 0 0
120 ! print_num(fac(10, id));
121 CONST 0
122 GLOBAL _id
123 CONST 10
124 CONST 0
125 GLOBAL _fac
126 PCALLW 3
127 CONST 0
128 GLOBAL lib.print_num
129 PCALL 1
130 ! newline()
131 CONST 0
132 GLOBAL lib.newline
133 PCALL 0
134 RETURN
135 END
136
137 ! String " * "
138 DEFINE g1
139 STRING 202A2000
140
141 ! String " = "
142 DEFINE g2
143 STRING 203D2000
144
145 ! End
146 ]]*)