方案:如何合并两个流

时间:2015-05-21 15:08:43

标签: scheme

我有这些功能

(define force!
  (lambda (thunk)
    (thunk)))


(define stream-head
  (lambda (s n)
    (if (zero? n)
        '()
        (cons (car s)
              (stream-head (force! (cdr s))
                           (1- n))))))

(define make-stream
  (lambda (seed next)
    (letrec ([produce (lambda (current)
                        (cons current
                              (lambda ()
                                (produce (next current)))))])
      (produce seed))))



(define make-traced-stream
  (lambda (seed next)
    (letrec ([produce (trace-lambda produce (current)
                        (cons current
                              (lambda ()
                                (produce (next current)))))])
      (produce seed))))

(define stream-of-even-natural-numbers
  (make-traced-stream 0
                      (lambda (n)
                        (+ n 2))))

(define stream-of-odd-natural-numbers
  (make-traced-stream 1
                      (lambda (n)
                        (+ n 2))))

我需要创建一个合并后两个的函数,这样如果我运行

(stream-head (merge-streams stream-of-even-natural-numbers stream-of-odd-natural-numbers) 10)

我必须得到输出(0 1 2 3 4 5 6 7 8 9)..这是怎么做的?

我最好的想法,这是错误的,是:

(define merge-streams
  (lambda (x y)
    (cons (car x)
          (merge-streams y (cdr x)))))

1 个答案:

答案 0 :(得分:2)

这是一个建议:

(define (merge-streams s1 s2)
  (cond
    [(empty-stream? s1) s2)] ; nothing to merge from s1
    [(empty-stream? s2) s1)] ; nothing to merge from s2
    [else (let ([h1 (stream-car s1)]
                [h2 (stream-car s2)])
            (cons h1 
              (lambda ()
                (cons h2 
                  (stream-merge (stream-rest s1) 
                                (stream-rest s2))))))]))

它使用一些必须首先定义的辅助函数。