无限流的累加器

时间:2019-03-08 07:41:02

标签: scheme lisp racket

我正在尝试为无限流实现累加器。我已经编写了以下代码,但是它正在陷入无限循环并且无法终止

(define (stream-first stream) (car stream))
(define (stream-second stream) (car ((cdr stream))))
(define (stream-third stream) (car ((cdr ((cdr stream))))))
(define (stream-next stream) ((cdr stream)))


(define (stream-foldl func accum stream)
    (cond
         [(empty? stream) accum]
         [else (stream-foldl func (func (stream-first stream) accum) (stream-next stream))] ))

我已经编写了一些测试来演示我要实现的目标

(define (natural-nums)
   (define (natural-nums-iter n)
   (thunk
   (cons n (natural-nums-iter (+ n 1)))))
   ((natural-nums-iter 0)))

(define x (stream-foldl cons empty (natural-nums)))
(check-equal? (stream-first x) empty)
(check-equal? (stream-second x) (list 0))
(check-equal? (stream-third x) (list 1 0))

(define y (stream-foldl (curry + 1) 10 (naturals)))
(check-equal? (stream-first y)  10)
(check-equal?  (stream-second y) 11)
(check-equal?  (stream-third y)  13)

这是我的流折叠功能的痕迹

>(stream-foldl
  #<procedure:cons>
  '()
  '(0 . #<procedure:...9/saccum.rkt:25:0>))
()>(stream-foldl
  #<procedure:cons>
  '(0)
  '(1 . #<procedure:...9/saccum.rkt:25:0>))
(0)>(stream-foldl
  #<procedure:cons>
  '(1 0)
  '(2 . #<procedure:...9/saccum.rkt:25:0>))
(1 0)>....

我认为我无法正确设置基本情况,因此永远不会终止递归调用

1 个答案:

答案 0 :(得分:3)

应该折叠查看流中的每个元素,然后根据这些元素产生结果。对于无限流,折叠不会终止也就不足为奇了(您如何看待无限流中的每个元素?)。

您可以做什么:

从无限流中产生有限流。 stream-take可用于此目的。 stream-take的示例实现:

;; Returns a stream containing the first n elements of stream s.
(define (stream-take n s)
  (cond ((zero? n) empty-stream)
        ((empty? s) (error "Stream is shorter than n")
        (else
          (delay (stream-first s)
                 (stream-take (- n 1) (stream-rest s)))))))
          ; Note: 'delay' is the same as the 'thunk' in your code.

然后,使用实现fold或stream-fold来折叠有限流。