2012-01-10 73 views
1

我一直在做一些功课,写了一些代码,实际上找不到它不工作的原因。这部分工作的主要思想是创建一个流,给我一个给定X(角度我猜)泰勒级数余弦函数的元素。反正这里是我的代码,我会很高兴,如果有人能指出我的原因,这是行不通的:)泰勒系列计划流

(define (force exp) exp) 
(define (s-car s) (car s)) 
(define (s-cdr s) (force (cdr s))) 

; returns n elements of stream s as a list 
(define (stream->list s n) 
    (if (= n 0) 
     '() 
     (cons (s-car s) (stream->list (s-cdr s) (- n 1))))) 

; returns the n-th element of stream s 
(define stream-ref (lambda (s n) 
        (if (= n 1) 
         (s-car s) 
         (stream-ref (s-cdr s) (- n 1))))) 

; well, the name kinda gives it away :) make factorial n! 
(define (factorial x) 
     (cond ((= x 0) 1) 
       ((= x 1) 1) 
       (else (* x (factorial (- x 1)))))) 

; this function is actually the equation for the 
; n-th element of Taylor series of cosine 
(define (tylorElementCosine x) 
    (lambda (n) 
    (* (/ (expt -1 n) (factorial (* 2 n))) (expt x (* 2 n))))) 

; here i try to make a stream of those Taylor series elements of cosine 
(define (cosineStream x) 
    (define (iter n) 
    (cons ((tylorElementCosine x) n) 
      (lambda() ((tylorElementCosine x) (+ n 1))))) 
    (iter 0)) 

; this definition should bind cosine 
; to the stream of taylor series for cosine 10 
(define cosine (cosineStream 10)) 
(stream->list cosine 10) 
; this should printi on screen the list of first 10 elements of the series 

但是,这并不工作,我不知道为什么。

我使用Dr.Scheme 4.2.5,并将语言设置为“Essentials of Programming Languages 3rd ed”。

+1

你认为“它不工作”是一个准确的失败描述?它究竟如何不起作用?你试过调试它吗? – Grizzly 2012-01-10 17:49:56

+0

是的我没有,一旦代码存在,这不是一个失败,90%的工作就像一个魅力,只有2个逻辑错误存在...没有dis-mate :) – 2012-01-10 18:14:24

回答

3

因为我感觉很好(对计划怀有怀疑),我实际上是通过代码来检查错误。从我所看到的有2个问题,这保持了代码,因为它应该运行:如果我理解你的代码正确(force exp)应该评估exp

,但是你直接返回它(未评估)。所以它可能应该定义为(define (force exp) (exp))

第二个问题是在你的lambda中:(lambda() ((tylorElementCosine x) (+ n 1)))将评估为泰勒系列的下一个元素,而它应该评估为流。你可能想要这样的东西:(lambda() (iter (+ n 1)))

我还没有检查输出是否正确,但它至少运行的修改。因此,如果代码中存在更多问题,则应该使用所使用的公式。

但是我建议下一次你需要家庭作业的帮助时,至少告诉我们问题出现的位置以及你已经尝试过的地方(社区确实皱着眉头“这是一些代码,请为我修复“种类的问题)。

+0

谢谢,这就像一个魅力工作...我对这两个错误都很不满:)对于这种蹩脚的问题,我第一次在这里问过帮助......我很少在编程方面提出帮助,因为我在大学里教C作为导师......非常感谢!我实际上犯了第一个错误,试图解决我唯一的错误,那就是lambda表达式... – 2012-01-10 18:18:43

+0

@nocgod:没有问题的问题风格,我只是不得不提及它,因为这些问题基本上说我有一个问题,请帮助我一般都不是那么受欢迎(由于显而易见的原因,听起来像请尽我所有工作)。所以在未来你可以更好地制定你的问题;) – Grizzly 2012-01-10 18:25:08

+0

肯定队友:)再次感谢您的帮助... – 2012-01-10 18:35:36