在Drracket中将#stream作为输出

时间:2015-10-14 07:05:20

标签: stream scheme racket

给出了订单和数据流,我需要根据order-stream订购数据。

#lang racket
(define the-empty-stream '())
(define (stream-car stream)
 (car stream))
(define-syntax cons-stream
 (syntax-rules ()
    ((cons-stream x y)
     (cons x (delay y)))))

(define (stream-cdr stream)
 (force (cdr stream)))
(define stream-null? null?)
(define (integers-starting-from n)
 (stream-cons n (integers-starting-from (+ n 1))))

(define integers (integers-starting-from 1))

(define order-stream (stream-cons 2 1))
(define data-stream (stream-cons 5 6))

(define (reorder order-stream data-stream)
 (cond ((stream-null? order-stream) the-empty-stream)
       ((stream-null? data-stream) the-empty-stream)
       (else (stream-cons (stream-ref data-stream 
                                      (stream-car order-stream))
                          (reorder (stream-cdr order-stream) data-stream)))))

当我执行(reorder order-stream data-stream)时,我将#stream作为输出而不是6 . #promise。这是我的编程任务,所以请提供一些提示,而不是提供完整的代码。

2 个答案:

答案 0 :(得分:2)

Racket有一个内置的stream-cons,你不小心打电话,而不是你打算使用的cons-stream

答案 1 :(得分:0)

看看你有什么:

(define (reorder order-stream data-stream)
                 ^^^^^^^^^^^^
 (cond ((stream-null? order-stream) the-empty-stream)
       ((stream-null? data-stream) the-empty-stream)
       (else (stream-cons (stream-ref data-stream 
                                      (stream-car order-stream))
                          (reorder (stream-cdr order-stream) data-stream)))))
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^

(define (stream-cdr stream)
 (force (cdr stream)))

期望(stream-cdr stream)返回什么样的东西?

然后你打电话

(define order-stream (cons-stream 2 1))

什么是order-stream' s cdr

流编程很有趣。例如,要计算流的部分和,p-s [a,b,c...] = a, a+b, a+b+c, ...,我们可以写

(define (partial-sums xs init)
    (cons-stream init 
         (partial-sums (stream-cdr xs)
                       (+ (stream-car xs) init))))

我们可以轻松地将+抽象为一般的二元运算参数:

(define (scanl + xs init)
    (cons-stream init 
              (scanl + (stream-cdr xs)
                       (+ (stream-car xs) init))))

并称之为,例如

(define factorials (scanl * integers 1))

定义scanl的另一种有趣的方式是

(define (scanlist + xs init)
   (define rs (cons-stream init 
                (combine-streams + xs rs)))
   rs)

在Haskell中编写combine-streams(a.k.a。zipWith)是一个简单的交易。

在Racket中,请务必使用完整语言,其中define是递归的,类似于letrec(不是let),否则最后一个不会工作(你能明白为什么吗?)