【发布时间】:2021-03-13 11:00:46
【问题描述】:
我正在尝试编写一个流,它以无限流S 和两个整数m 和n 作为参数,并返回其元素是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,所以我不明白我哪里出错了。任何想法将不胜感激。
【问题讨论】:
标签: stream scheme racket lazy-sequences