gpt4 book ai didi

stream - Scheme中的流问题

转载 作者:行者123 更新时间:2023-12-04 08:29:31 26 4
gpt4 key购买 nike

我正在尝试编写一个将无限流作为参数的流 S , 和两个整数 mn , 并返回其元素是 S 元素的流是 m 的倍数或 n .
不幸的是,我的流仅在我找到第一个倍数之前有效,然后它不会超过那个。我调用 cdr调用流时,所以我不确定为什么不查看下一个元素。

(define stream-car car)
(define (stream-cdr s)
((cadr s)))

(define (divisible? n x)
(zero? (remainder n x)))
(define (stream-cons x s)
(list x (lambda () s)))

;should loop to find the next multiple in the parameter stream
(define (findnext s m n)
(if (or (divisible? (stream-car s) m)
(divisible? (stream-car s) n))
(stream-car s)
(findnext (stream-cdr s) m n)))

;this is my stream
(define (multiples s m n)
(let ((h (findnext s m n)))
;first need to make sure h is a multiple of
;either m or n, THEN create the list
(list h
(lambda ()
(multiples (stream-cdr s) m n)))))

;below is for testing
(define (even-nums-from n)
(list n
(lambda ()
(even-nums-from (+ 2 n)))))

(define even-integers
(even-nums-from 0))

;test cases
(multiples even-integers 4 6);should be a stream with car = 0
(stream-car (multiples even-integers 4 6));should be 0
(stream-cdr (multiples even-integers 4 6));should be a stream with car = 4
(stream-car (stream-cdr (multiples even-integers 4 6))) ;should be 4
(stream-cdr (stream-cdr (multiples even-integers 4 6))) ;should be a stream
;starting with 6-not moving past when we find a multiple
(stream-car (stream-cdr (stream-cdr (multiples even-integers 4 6))))
;should be 6
我对上述测试的输出是:
(list 0 (lambda () ...))
0
(list 4 (lambda () ...))
4
(list 4 (lambda () ...))
4
我正在使用 DrRacket(高级学生语言),只是不确定为什么我的流卡在第一个倍数 (4) 上。当我再次调用 multiples 时,我正在调用 stream-cdr,所以我不明白我哪里出错了。任何想法将不胜感激。

最佳答案

解决了它,问题是我没有更新传递的流,因为我找到了下一个倍数。下面是更正后的代码(我现在在其中传递了一个带有车内倍数的流,将在我的 multiples 函数中使用):

;returns the stream with car a multiple of either m or n
(define (findnext s m n)
(cond ((divisible? (stream-car s) m) s)
((divisible? (stream-car s) n) s)
(else (findnext (stream-cdr s) m n))))

(define (multiples s m n)
(let ((h (findnext s m n))) ;h is now an updated stream
;with car a multiple of one of m or n
(list (stream-car h)
(lambda ()
(multiples (stream-cdr h) m n)))))

关于stream - Scheme中的流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65091929/

26 4 0