looking for some solutions? You are welcome.

SOLVED: Accumulator for infinite streams

Ron Marchant:

I'm trying to implement an accumulator for an infinite stream. I've written the following code but it's running into an infinite loop and failing to terminate

(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))] ))

I've written up a few tests to demonstrate what I'm trying to implement

(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)

Here's a trace of my stream-foldl function

>(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)>....

I believe I'm failing to properly set a base case, thus never terminating from the recursion call



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent