Long story, bear with me. I am working through SICP in Arc. I got to the Fixed Points of Functions section in Chapter 1. http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html The example used sine and cosine. I decided to define my own using the accumulate function from earlier in SICP: (def accumulate (combiner null-value term a next b)
(def iter (a result)
(if (> a b) result
(iter (next a) (combiner (term a) result))))
(iter a null-value))
(def sum (term a next b)
(accumulate + 0 term a next b))
(def product (term a next b)
(accumulate * 1 term a next b))
(def identity(v) v)
(def inc(x) (+ x 1))
(def factorial(n)
(product identity 1 inc n))
(def exp(n power)
(product (fn (x) n) 1 inc power))
(= iterations 100)
; Distinguisher is the difference between the cos and sine terms
(def cos-sine-term(x n distinguisher)
(/ (* (exp -1.0 n)(exp x (distinguisher n)))
(factorial (distinguisher n))))
(def cosine-distinguisher(n) (* 2 n))
(def sine-distinguisher(n) (inc (cosine-distinguisher n)))
(def cos-sine(x distinguisher)
(sum (fn (n) (cos-sine-term x n distinguisher)) 0 inc iterations))
(def cos(x)
(cos-sine x cosine-distinguisher))
(def sin(x)
(cos-sine x sine-distinguisher))
Unfortunately it blew up. Yet when I tested each individual piece, no trouble.I suspected that it had something to do with iter, and maybe that the wrong iter was being used at times. So, I made a lambda version. (Halfway to a a Y Combinator! Too bad my Y Combinator version is broken) (def accumulate (combiner null-value term a next b)
(((fn (f)
(fn (a result)
(if (> a b) result
((f f) (next a) (combiner (term a) result)))))
(fn (f)
(fn (a result)
(if (> a b) result
((f f) (next a) (combiner (term a) result))))))
a
null-value))
This version works as expected.I'm very new to this, but shouldn't the inline def version work the same as the lambda version? |