level 2
Wiikeen
楼主
使用无限流来定义一些我们喜欢的序列。在下面为您定义了函数combine-with,以及如何使用它定义偶数流的示例。
(define (naturals n)
(cons-stream n (naturals (+ n 1))))
(define (combine-with f xs ys)
(if (or (null? xs) (null? ys))
nil
(cons-stream
(f (car xs) (car ys))
(combine-with f (cdr-stream xs) (cdr-stream ys)))))
(define (slice s start end)
(define (helper s n start end)
(cond
((null? s) nil)
((>= n end) nil)
((< n start) (helper (cdr-stream s) (+ n 1) start end))
((>= n start) (cons (car s) (helper (cdr-stream s) (+ n 1) start end)))
)
)
(helper s 0 start end))scm> (define evens (combine-with + (naturals 0) (naturals 0)))
evens
scm> (slice evens 0 10)
(0 2 4 6 8 10 12 14 16 18)
对于一下问题,请使用combine-with和naturals流组成新的序列。
1、(slice factorials 0 10) ---> (1 1 2 6 24 120 720 5040 40320 362880)
(define factorials
2、(slice fibs 0 10) ---> (0 1 1 2 3 5 8 13 21 34)
(define fibs
有大神可以指点一下我吗?
2020年02月25日 06点02分
1
(define (naturals n)
(cons-stream n (naturals (+ n 1))))
(define (combine-with f xs ys)
(if (or (null? xs) (null? ys))
nil
(cons-stream
(f (car xs) (car ys))
(combine-with f (cdr-stream xs) (cdr-stream ys)))))
(define (slice s start end)
(define (helper s n start end)
(cond
((null? s) nil)
((>= n end) nil)
((< n start) (helper (cdr-stream s) (+ n 1) start end))
((>= n start) (cons (car s) (helper (cdr-stream s) (+ n 1) start end)))
)
)
(helper s 0 start end))scm> (define evens (combine-with + (naturals 0) (naturals 0)))
evens
scm> (slice evens 0 10)
(0 2 4 6 8 10 12 14 16 18)
对于一下问题,请使用combine-with和naturals流组成新的序列。
1、(slice factorials 0 10) ---> (1 1 2 6 24 120 720 5040 40320 362880)
(define factorials
2、(slice fibs 0 10) ---> (0 1 1 2 3 5 8 13 21 34)
(define fibs
有大神可以指点一下我吗?