Lisp/Scheme programming language | INFJ Forum

Lisp/Scheme programming language

Discussion in 'Computer Science' started by corvidae, Jun 30, 2009.

Share This Page

More threads by corvidae
  1. corvidae

    corvidae ohai internets
    Donor

    Joined:
    Dec 23, 2008
    Threads:
    60
    Messages:
    806
    Likes Received:
    53
    Trophy Points:
    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++
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
Loading...

Share This Page