comparison lab4/test/sumpower.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 (* Higher-order functions *)
2
3 proc sum(a, b: integer; proc f(x: integer): integer): integer;
4 var i, s: integer;
5 begin
6 i := a; s := 0;
7 while i <= b do
8 s := s + f(i);
9 i := i + 1
10 end;
11 return s
12 end;
13
14 proc sum_powers(a, b, n: integer): integer;
15 proc pow(x: integer): integer;
16 var j, p: integer;
17 begin
18 j := 0; p := 1;
19 while j < n do
20 p := p * x;
21 j := j + 1
22 end;
23 return p
24 end;
25 begin
26 return sum(a, b, pow)
27 end;
28
29 begin
30 print_num(sum_powers(1, 10, 3));
31 newline()
32 end.
33
34 (*<<
35 3025
36 >>*)
37
38 (*[[
39 @ picoPascal compiler output
40 .include "fixup.s"
41 .global pmain
42
43 @ proc sum(a, b: integer; proc f(x: integer): integer): integer;
44 .text
45 _sum:
46 mov ip, sp
47 stmfd sp!, {r0-r3}
48 stmfd sp!, {r4-r10, fp, ip, lr}
49 mov fp, sp
50 @ i := a; s := 0;
51 ldr r4, [fp, #40]
52 mov r5, #0
53 .L2:
54 @ while i <= b do
55 ldr r0, [fp, #44]
56 cmp r4, r0
57 bgt .L4
58 @ s := s + f(i);
59 mov r0, r4
60 ldr r10, [fp, #52]
61 ldr r1, [fp, #48]
62 blx r1
63 add r5, r5, r0
64 @ i := i + 1
65 add r4, r4, #1
66 b .L2
67 .L4:
68 @ return s
69 mov r0, r5
70 ldmfd fp, {r4-r10, fp, sp, pc}
71 .ltorg
72
73 @ proc sum_powers(a, b, n: integer): integer;
74 _sum_powers:
75 mov ip, sp
76 stmfd sp!, {r0-r3}
77 stmfd sp!, {r4-r10, fp, ip, lr}
78 mov fp, sp
79 @ return sum(a, b, pow)
80 mov r3, fp
81 set r2, _pow
82 ldr r1, [fp, #44]
83 ldr r0, [fp, #40]
84 bl _sum
85 ldmfd fp, {r4-r10, fp, sp, pc}
86 .ltorg
87
88 @ proc pow(x: integer): integer;
89 _pow:
90 mov ip, sp
91 stmfd sp!, {r0-r1}
92 stmfd sp!, {r4-r10, fp, ip, lr}
93 mov fp, sp
94 @ j := 0; p := 1;
95 mov r4, #0
96 mov r5, #1
97 .L7:
98 @ while j < n do
99 ldr r0, [fp, #24]
100 ldr r0, [r0, #48]
101 cmp r4, r0
102 bge .L9
103 @ p := p * x;
104 ldr r0, [fp, #40]
105 mul r5, r5, r0
106 @ j := j + 1
107 add r4, r4, #1
108 b .L7
109 .L9:
110 @ return p
111 mov r0, r5
112 ldmfd fp, {r4-r10, fp, sp, pc}
113 .ltorg
114
115 pmain:
116 mov ip, sp
117 stmfd sp!, {r4-r10, fp, ip, lr}
118 mov fp, sp
119 @ print_num(sum_powers(1, 10, 3));
120 mov r2, #3
121 mov r1, #10
122 mov r0, #1
123 bl _sum_powers
124 bl print_num
125 @ newline()
126 bl newline
127 ldmfd fp, {r4-r10, fp, sp, pc}
128 .ltorg
129
130 @ End
131 ]]*)