SHOW:
|
|
- or go back to the newest paste.
1 | - | #lang racket |
1 | + | #lang racket |
2 | - | |
2 | + | |
3 | - | (require rackunit) |
3 | + | (require rackunit) |
4 | - | |
4 | + | |
5 | - | ; A fixed point of f is x such that f(x) = x. |
5 | + | ; A fixed point of f is x such that f(x) = x. |
6 | - | ; We need to develop means to get a fixed point of f. |
6 | + | ; We need to develop means to get a fixed point of f. |
7 | - | |
7 | + | |
8 | - | ;; Curry's Paradoxical Combinator of Y |
8 | + | ;; Curry's Paradoxical Combinator of Y |
9 | - | (define (Y f) |
9 | + | (define (Y f) |
10 | - | ((λ (r) (f (delay r r))) |
10 | + | ((λ (r) (f (delay r r))) |
11 | - | (λ (r) (f (delay r r))))) |
11 | + | (λ (r) (f (delay r r))))) |
12 | - | |
12 | + | |
13 | - | ; (Y F) = (F (F (... (Y F)))) |
13 | + | ; (Y F) = (F (F (... (Y F)))) |
14 | - | ; Y produces the fixed point of F |
14 | + | ; Y produces the fixed point of F |
15 | - | |
15 | + | |
16 | - | ;; Recursive exponentiation via Y-combinator |
16 | + | ;; Recursive exponentiation via Y-combinator |
17 | - | (define (pow r) |
17 | + | (define (pow r) |
18 | - | (λ (x n) |
18 | + | (λ (x n) |
19 | - | (define next-call ((force r) (force r))) |
19 | + | (define next-call ((force r) (force r))) |
20 | - | (cond ((= n 0) 1) |
20 | + | (cond ((= n 0) 1) |
21 | - | (else (* x (next-call x (sub1 n))))))) |
21 | + | (else (* x (next-call x (sub1 n))))))) |
22 | - | |
22 | + | |
23 | - | ;; Base to the power of exponent |
23 | + | ;; Base to the power of exponent |
24 | - | (define (power base exponent) |
24 | + | (define (power base exponent) |
25 | - | ((Y pow) base exponent)) |
25 | + | ((Y pow) base exponent)) |
26 | - | |
26 | + | |
27 | - | ;; Tests |
27 | + | ;; Tests |
28 | - | (check-equal? (power 0 99) 0) |
28 | + | (check-equal? (power 0 99) 0) |
29 | - | (check-equal? (power 1 99) 1) |
29 | + | (check-equal? (power 1 99) 1) |
30 | - | (check-equal? (power 2 4) 16) |
30 | + | (check-equal? (power 2 4) 16) |
31 | - | (check-equal? (power 3 3) 27) |
31 | + | (check-equal? (power 3 3) 27) |
32 | (check-equal? (power 10 5) 100000) |