Reputation: 11
I want to write a procedure that rearranges the items in one stream (the data stream) into the order specified by another stream (the order stream), which consists of item numbers specifying the desired order.
For example, if the data stream starts with 4, 13, 2, 8 and the order stream starts with 3, 1, 4, 2 then the result stream will start with 2, 4, 8, 13. (The first item of the result is the third item of the data, the second item of the result is the first item of the data, and so on.)
I have got so far...
(define (reorder order-stream data-stream)
(cond ((stream-null? order-stream) the-empty-stream)
((stream-null? data-stream) the-empty-stream)
(else (cons-stream (stream-ref order-stream data-stream))))
(define (stream-ref s n)
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
However, the output is not as expected.
Upvotes: 1
Views: 429
Reputation: 31147
Using Racket streams.
Notice that
(stream-ref data-stream (stream-first order-stream))
will use the first element of the order stream to pick out an element of the data stream.
Note also that unless the data stream support random access, this will be we slow.
#lang racket
(require racket/stream)
(define (reorder order-stream data-stream)
(cond ((stream-empty? order-stream) empty-stream)
(else (stream-cons (stream-ref data-stream (stream-first order-stream))
(reorder (stream-rest order-stream) data-stream)))))
(define ones (stream-cons 1 ones))
(define (stream-add s1 s2)
(stream-cons (+ (stream-first s1) (stream-first s2))
(stream-add (stream-rest s1) (stream-rest s2))))
(define fibonacci (stream-cons 1 (stream-cons 1 (stream-add fibonacci (stream-rest fibonacci)))))
(for/list ([x fibonacci] [n 10]) x) ; '(1 1 2 3 5 8 13 21 34 55)
(for/list ([x (reorder '(3 1 4 2 10) fibonacci)]) x) ; '(3 1 5 2 89)
Upvotes: 1