SICP练习3.51要应用的类型错误:#<syntax-transformer cons-stream =“”>

时间:2018-04-27 07:50:26

标签: scheme sicp guile

在SICP的练习3.51中,它定义了一个过程&#34; show&#34;,并使用stream-map创建一个流:

(add-to-load-path ".")
(load "stream.scm")

(define (show x)
  (display-line x)
  x)

(define x0 (stream-enumerate-interval 0 3))

(display-stream x0)   ;succ, no error

(stream-map show x0)  ;all element printed, but interpreter report error at last

其他工作人员关于stream.scm中的流:

#!/usr/bin/guile
!#

(define (stream-null? s)
  (null? s))

(define (stream-ref s n)
  (if (= n 0)
      (stream-car s)
      (stream-ref (stream-cdr s) (- n 1))))

(define (stream-map proc s)
  (if (stream-null? s)
      the-empty-stream
      (cons-stream (proc (car s))
                   (stream-map proc (stream-cdr s)))))

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

(define (display-stream s)
  (stream-for-each display-line s))

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

(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))

(define (stream-enumerate-interval low high)
  (if (> low high)
      the-empty-stream
      (cons-stream
        low
        (stream-enumerate-interval (+ low 1) high))))

(define (stream-filter pred stream)
  (cond
    ((stream-null? stream) the-empty-stream)
    ((pred (stream-car stream))
     (cons-stream (stream-car stream)
                  (stream-filter pred (stream-cdr stream))))
    (else
      (stream-filter pred (stream-cdr stream)))))

(define-syntax cons-stream
  (syntax-rules ()
    ((_ a b) (cons a (delay b)))))

(define the-empty-stream '())

(define (stream-enumerate-interval low high)
  (if (> low high)
      the-empty-stream
      (cons-stream low
                   (stream-enumerate-interval (+ low 1) high))))

错误是这样的:

0123Backtrace:
           8 (apply-smob/1 #<catch-closure 557e16ae8c20>)
In ice-9/boot-9.scm:
    705:2  7 (call-with-prompt ("prompt") #<procedure 557e16aef6a0 …> …)
In ice-9/eval.scm:
    619:8  6 (_ #(#(#<directory (guile-user) 557e16b9e140>)))
In ice-9/boot-9.scm:
   2312:4  5 (save-module-excursion #<procedure 557e16b24330 at ice-…>)
  3822:12  4 (_)
In stream.scm:
     25:8  3 (stream-map #<procedure show (x)> (0 . #<promise (1 . …>))
     25:8  2 (stream-map #<procedure show (x)> (1 . #<promise (2 . …>))
     25:8  1 (stream-map #<procedure show (x)> (2 . #<promise (3 . …>))
In unknown file:
           0 (_ 3 ())

我不知道为什么显示流成功,但是流映射&#34;显示&#34;失败了。 代码与SICP中的示例相同。计划翻译是#guile&#39;

有什么想法吗? THX

1 个答案:

答案 0 :(得分:1)

移动时错误消失

(define-syntax cons-stream
  (syntax-rules ()
    ((_ a b) (cons a (delay b)))))

到文件的顶部。

显然,在Guile中,必须将其定义在文件中的第一个使用点之上。

您没有看到stream-enumerate-interval的错误,因为它已定义两次 - 上次以下 cons-stream的定义

使用&#34; guile 2.0.13&#34; https://ideone.com进行了测试。