Lisp/Scheme programming language | INFJ Forum

Lisp/Scheme programming language

corvidae

ohai internets
Donor
Dec 23, 2008
806
55
0
MBTI
INTJ
Enneagram
?
Exercise 1.11. A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.

Code:
(define (f n)
  (cond ((< n 3) n)
        (else (+ (f (- n 1)) (* 2 (f (- n 2))) ( * 3 (f (- n 3)))))))

(define (f-new x)
  (f-iter x 0 0 0 x))

(define (f-iter x a b c roof)
  (cond ((< x 3) x)
        (else
         (cond ((= a 0) (f-iter x 1 2 3 (- roof 1)))
               (else
                (cond ((= 2 roof) (+ b (* 2 a)))
                      (else
                       (f-iter x (+ b a) (+ c (* 2 a)) (* 3 a) (- roof 1)))))))))

YAY I GOT IT. Even though it literally ends with nine parentheses it's still somewhat elegant.

Scheme is so much more fun than Java or C++
 
  • Like
Reactions: Jexocuha