Recursive call from Condition Branch

81 views Asked by At

I'm starting to get to grips with Lisp and I'm trying to write a procedure to approximate pi using the Leibniz formula at the moment; I think I'm close but I'm not sure how to proceed. The current behavior is that it makes the first calculation correctly but then the program terminates and displays the number '1'. I'm unsure if I can call a defined function recursively like this,

;;; R5RS
(define (pi-get n)
  (pi 0 1 n 0))

(define (pi sum a n count)
  ;;; if n == 0, 0
  (if (= n 0) 0)
  ;;; if count % 2 == 1, + ... else -, if count == n, sum
  (cond ((< count n)
         (cond ((= (modulo count 2) 1)
                (pi (+ sum (pi-calc (+ 2 a))) (+ a 2) n (+ count 1)))
               (pi
                (- sum (pi-calc (+ 2 a))) (+ a 2) n (+ count 1))))))

(define (pi-calc a)
  (/ 1.0 a))

Apologies if this is a little unreadable, I'm just learning Lisp a few weeks now and I'm not sure what normal formatting would be for the language. I've added a few comments to hopefully help.

1

There are 1 answers

4
I2obiN On BEST ANSWER

As Sylwester mentioned it turned out to be a mistake on my part with syntax.

;;; R5RS
(define (pi-get n)
 (pi 1 1 n 0))

(define (pi sum a n count)
(if (= n 0) 0)
(cond ((< count n)
     (cond ((= (modulo count 2) 1)
            (pi (+ sum (pi-calc (+ 2 a))) (+ a 2) n (+ count 1)))
           ((= (modulo count 2) 0)
            (pi (- sum (pi-calc (+ 2 a))) (+ a 2) n (+ count 1))))
(display (* 4 sum)) (newline))))

(define (pi-calc a)
 (/ 1.0 a))