;(1)
(define sum
(lambda (lst)
(if (null? lst)
0
(+ (car lst) (sum (cdr lst))))))
; 別解
(define sum
(lambda (lst)
(define sum2
(lambda (lst1 ans)
(if (null? lst1)
ans
(sum2 (cdr lst1) (+ ans (car lst1))))))
(sum2 lst 0)))
;(2)
(define size
(lambda (lst)
(if (null? lst)
0
(+ 1 (size (cdr lst))))))
; 別解
(define size
(lambda (lst)
(define size2
(lambda (lst1 ans)
(if (null? lst1)
ans
(size2 (cdr lst1) (+ 1 ans)))))
(size2 lst 0)))
; (3)
(define average
(lambda (lst)
(if (null? lst)
#f
(/ (sum lst) (size lst)))))
; (4)
(define even
(lambda (lst)
(if (null? lst)
()
(if (even? (car lst))
(cons (car lst) (even (cdr lst)))
(even (cdr lst))))))
; (5)
(define skip
(lambda (lst)
(if (null? lst)
()
(cons (car lst) (skip1 (cdr lst))))))
(define skip1
(lambda (lst)
(if (null? lst)
()
(skip (cdr lst)))))
; (6)
(define my-reverse
(lambda (lst)
(define reverse2
(lambda (lst stack)
(if (null? lst)
stack
(reverse2 (cdr lst) (cons (car lst) stack)))))
(reverse2 lst ())))
; (7)
(define draw-four
(lambda (lst)
(define draw-four3
(lambda (lst1 sum max)
(if (null? lst1)
(if (< sum max)
max
sum)
(if (= (car lst1) 4)
(draw-four3 (cdr lst1) (+ sum 4) max)
(if (< sum max)
(draw-four3 (cdr lst1) 0 max)
(draw-four3 (cdr lst1) 0 sum))))))
(draw-four3 lst 0 0)))
|