-2

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.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
I2obiN
  • 181
  • 3
  • 18

1 Answers1

0

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))
I2obiN
  • 181
  • 3
  • 18
  • 1
    `if` versus `cond` has nothing to do with it. You had too few parentheses for the `cond` and in bot your original post and this you are ignoring cases which ends up as undefined values instead of answers. In particular the printing in the end is what makes the return value so it will always be undefined. – Sylwester Dec 17 '16 at 02:23
  • It's strange because Racket didn't give me a syntax error and still doesn't. Also I believe I understand now that I should have defined sum if I wanted to return an actual value. – I2obiN Dec 17 '16 at 17:54
  • It was valid because the parentheses around the last `pi` became the term instead of calling the procedure it evaluated the procedure as the predicate and the arguments became the consequent expressions.. No syntax error but hardly the intent. See how I formatted your original code. – Sylwester Dec 17 '16 at 18:14
  • One more question regards sum. Should I define it? What is best practice here? – I2obiN Dec 17 '16 at 18:17