请教一下大神们这一题怎么解,想了好久都想不出来。
scheme吧
全部回复
仅看楼主
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
level 2
Wiikeen 楼主
我找到答案啦!
1、(define factorials (combine-with (lambda (x y) (if (= 0 (* x y)) 1 (* x y))) (naturals 0) (cons-stream 0 factorials)))
2、(define fibs (combine-with + (cons-stream 0 (cons-stream 1 fibs)) (cons-stream 0 fibs)))
2020年02月27日 09点02分 2
1