straight recursion: (define (Tri-1 N) (if (= N 1) 1 (+ N (Tri-1 (- N 1))))) iterative recursion: (define (Tri-2-helper Target Pos Sub) (if (= Pos Target) Sub (Tri-2-helper Target (+ 1 Pos) (+ Sub 1 Pos)))) (define (Tri-2 N) (Tri-2-helper N 1 1))
Recursion
on Lists:
Here's how we created our function MyLength(L) that returned the number of elements
in a list (assuming that we didn't have access to the built-in
Scheme function length):
(define (MyLength L) (if (null? L) 0 (+ 1 (MyLength (cdr L))))) (MyLength '(A (B C) D)) ;-> 3Here's how we add up a bunch of numbers in a list:
(define (AddNumbers L) (if (null? L) 0 (+ (car L) (AddNumbers (cdr L))))) (AddNumbers '(12 -2 4)) ;-> 14Here's how we create a list of N numbers in increasing order starting at 1 (assume N >= 1). Example:
(Sequence 5) ;-> (1 2 3 4 5)
(define (Sequence N) (if (= N 1) '(1) (append (Sequence (- N 1)) (list N))))
(MultNumbers '(2 5 8)) ;-> 80
4) We're (well, actually, you're) going to create two new versions of the
factorial function.
4a) Do it with iterative recursion.
4b) Use MultNumbers.
5) Create the list function MyReverse(L) which will do the same thing as the built-in function Reverse. (Don't even think about using Reverse.) Example:
(Reverse '(A 12 My foot)) ;-> (foot My 12 A)
6) Create the function Explode(N) which is given a non-negative number and creates a list of its digits. Example:
(Explode 263) ;-> (2 6 3) (Explode 8) ;-> (8)
7) (harder) Create the function Implode(L) which will be given a non-empty list of digits, and will create the corresponding number from it. Example:
(Implode '(2 6 3)) ;-> 263 (Implode '(8)) ;-> 8