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,语言设置为“第三版编程语言要点”。

4

1 回答 1

3

由于我感觉很好(并且对方案感到怀念),我实际上是通过您的代码来查找错误。据我所知,有两个问题使代码无法正常运行:

如果我正确理解您的代码(force exp)应该评估exp,但是您直接返回它(未评估)。所以它可能应该定义为(define (force exp) (exp))

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

我还没有检查输出是否正确,但是通过这些修改,它至少可以运行。因此,如果代码还有其他问题,则应该在使用的公式中。

但是,我建议下次您在作业方面需要帮助时,您至少告诉我们问题的具体表现在哪里以及您已经尝试过什么(社区确实对“这里有一些代码,请为我修复”之类的问题皱眉)。

于 2012-01-10T18:06:11.897 回答