我将如何实现重复功能,该功能将使流程充满重复INT?
问题是:编写一个函数(重复X),该函数在给定值x的情况下会产生一个重复x ad infinitum的流。例如,呼叫(取(重复42)5)产生(42 42 42 42 42 42)。
我的问题是我的重复功能不知道该停止什么...因此它永远运行。
这是我到目前为止的代码。
#lang R5RS
;; Repeat your solution for take
(define (integer-stream x)
(cons x (delay (integer-stream (+ 1 x)))))
(define nat (integer-stream 0))
(define (stream-car stream)
(car stream))
(define (stream-cdr stream)
(force (cdr stream)))
(define (head stream) (car stream))
(define (rest stream) (force (cdr stream)))
(define (take s k)
(cond ((= k 0) '())
(else (cons (car s) (take (stream-cdr s) (- k 1))))))
;;;;;;;;;
(define (stream-map f s)
(if (null? s) '()
(cons (f (car s))
(delay (stream-map f (rest s))))))
(define (squares x)
(* x x))
(define (square s)
(cond ((null? s) '())
(else (stream-map squares s))))
;;;;;;;;;;;
(define (cubess x)
(* x x x))
(define (cube s)
(cond ((null? s) '())
(else (stream-map cubess s))))
;;;;
(define (merge-streams s t)
(cond ((null? s) t)
((null? t) s)
((< (stream-car s) (stream-car t))
(cons (stream-car s)
(delay (merge-streams (stream-cdr s) t))))
(else (cons (stream-car t) (delay (merge-streams s (stream-cdr t)))))))
;;;;;
(define (repeat x)
(cons x (repeat x)))
The questions is: Write a function (repeat x) which, given a value x, produces a stream that repeats x ad infinitum. For instance, the call (take (repeat 42) 5) produces (42 42 42 42 42).
My problem is that my repeat function doesn't know what to stop... so it runs forever.
This is the code I have so far.
#lang R5RS
;; Repeat your solution for take
(define (integer-stream x)
(cons x (delay (integer-stream (+ 1 x)))))
(define nat (integer-stream 0))
(define (stream-car stream)
(car stream))
(define (stream-cdr stream)
(force (cdr stream)))
(define (head stream) (car stream))
(define (rest stream) (force (cdr stream)))
(define (take s k)
(cond ((= k 0) '())
(else (cons (car s) (take (stream-cdr s) (- k 1))))))
;;;;;;;;;
(define (stream-map f s)
(if (null? s) '()
(cons (f (car s))
(delay (stream-map f (rest s))))))
(define (squares x)
(* x x))
(define (square s)
(cond ((null? s) '())
(else (stream-map squares s))))
;;;;;;;;;;;
(define (cubess x)
(* x x x))
(define (cube s)
(cond ((null? s) '())
(else (stream-map cubess s))))
;;;;
(define (merge-streams s t)
(cond ((null? s) t)
((null? t) s)
((< (stream-car s) (stream-car t))
(cons (stream-car s)
(delay (merge-streams (stream-cdr s) t))))
(else (cons (stream-car t) (delay (merge-streams s (stream-cdr t)))))))
;;;;;
(define (repeat x)
(cons x (repeat x)))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您很接近 - 您只需要使用
delay
在您的中重复
函数:其余代码应相同 - 因此,这将是完整的代码:
test:test:
You're close- you just have to use
delay
in yourrepeat
function:Rest of code should be the same- so this will be the full code:
Test: