This is a course page of David Casperson |
|
From time to time I shall post solutions to homework problems here.
fun power (x,n) = let fun pow3 (_,0,a) = a | pow3 (x,1,a) = x*a | pow3 (x,n,a) = let val d = (case n mod 2 of 0 => a | 1 => x*a) in pow3(x, n div 2,d) end in pow3(x,n,1.0) endThis uses
case
which we haven't formally looked
at, but the
meaning should be apparent. We could equivalently write
fun power (x,n) = let fun pow3 (_,0,a) = a | pow3 (x,1,a) = x*a | pow3 (x,n,a) = let val d = (if n mod 2 = 0 then a else x*a) in pow3(x, n div 2,d) end in pow3(x,n,1.0) end
letrec
to
define a local function with an accumulator.
(define (reverse a-list) (letrec ((reverse2 (lambda (b-list answer) (cond ((null? b-list) answer) ((cons? b-list) (reverse2 (cdr b-list) (cons (car b-list) answer))))) )) (reverse2 a-list '())))Slightly more strait-forward is
(define (reverse a-list) (reverse2 a-list '())) (define (reverse2 b-list answer) (cond ((null? b-list) answer) ((cons? b-list) (reverse2 (cdr b-list) (cons (car b-list) answer)))) ))
(define (foldr f b a-list) (cond ((null? a-list) b) (else (f (car a-list) (foldr f b (cdr a-list))))))
fall-2024