关于显示无限流的连续项的问题

时间:2012-01-28 19:41:04

标签: stream lisp scheme

; defining stream-for-each
(define (stream-for-each proc s)
  (if (stream-null? s)
      'done
      (begin (proc (stream-car s))
        (stream-for-each (stream-cdr s)))))

; Defining a method to display the stream
(define (display-stream s)
  (stream-for-each display-line s))

(define (display-line x)
  (newline)
  (display x))

; Creating a stream that uses Newton-Raphson
; method to find the Square Root of 2
(define (sqrt-improve guess x)
  (avg guess (/ x guess)))

(define (sqrt-stream x)
  (define guesses
    (cons-stream 1.0
                 (stream-map (lambda (guess)
                              (sqrt-improve guess x))
                             guesses)))
  guesses)

现在正在测试..

=> (stream-ref (sqrt-stream 2) 11)
Value: 1.414213562373095

所以似乎流正常工作;但是,当我尝试显示它时:

=> (display-stream (sqrt-stream 2))
1.
;The procedure #[compound-procedure 13 stream-for-each] 
has been called with 1 argument; it requires exactly 2 arguments.

从我看到的,每个流都被称为2个args,但我必须遗漏一些东西。我将不胜感激任何澄清。代码取自:http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#%_sec_3.5.3

1 个答案:

答案 0 :(得分:3)

你只是在递归调用(stream-for-each (stream-cdr s))中错过了一个参数。您的函数stream-for-each的合约为procedure? stream? -> 'done,但您只提供了一个流(错误就是这样)。