-
;;; = greatest common divisor of x, y
(define (gcd x y)
(cond ((= x 0) y)
((= y 0) x)
((= x y) x)
((> x y) (gcd (- x y) y))
((< x y) (gcd x (- y x)))))
-
;;; = 2nd to last element of alist, or null if alist has < 2 elements
(define (2nd-last alist)
(if (< (length alist) 2)
()
(cadr (reverse alist))))
-
;;; = sum of digits in decimal representation of n
(define (decimal-digit-sum n)
(if (= n 0)
0
(+ (modulo n 10)
(decimal-digit-sum (quotient n 10)))))
;;; = sum of the digits of integers in alist
;;; (this handles negative numbers, but that was not required)
(define (sum-digits alist)
(if (null? alist)
0
(+ (if (number? (car alist))
(decimal-digit-sum (abs (car alist)))
0)
(sum-digits (cdr alist)))))
-
;;; = depth of alist
(define (depth alist)
(if (pair? alist)
(max (+ 1 (depth (car alist)))
(depth (cdr alist)))
0))
-
;;; = nth fibonocci number (efficiently)
(define (fib n)
(tail-fib n 0 1))
;;; given the current and next number in the fibonocci sequence,
;;; return the fibonocci number that is k numbers further in the sequence.
;;; (k=0 means return the current number, k=1 means the next one, etc.)
(define (tail-fib k current next)
(if (= k 0)
current
(tail-fib (- k 1) next (+ current next))))