如何定义一个过程返回无限流 <div class="navigation-heading">\n<span>\n <span>$1</span>\n</span>\n</div>
中的所有元素对?
s = {1,2,3,4,5,6,...}
=&GT; {(2,1),(3,2),(3,1),(4,3),(4,2),(4,1),......}
这是我的代码,但是它不像流一样工作,它会无限运行并且耗尽内存。
s
A = {1,2,4,8,16,......}
答案 0 :(得分:1)
事实证明,Racket的stream-append
不会延迟其最后(至少)参数,因此iter
调用stream-append
调用iter
...因此循环。
一种方法是重新实现与此处使用的stream-append
融合的stream-map
,作为一个简单的递归函数。这样尾巴就会在延迟stream-cons
的保护下正确。
另一个是假冒stream-rest
的{{1}} 1 :
stream-cons
此外,您的代码中还有另一个错误,即使用(require racket/stream)
(define (stream-pairs s)
(define (iter s save)
(stream-append (stream-map (lambda (x) (list (stream-first s) x))
save) ;^^^^
(stream-rest
(stream-cons 'fake ;<<-----------------
(iter (stream-rest s)
(stream-cons (stream-first s) save))))))
(iter s empty-stream))
(define A (stream-cons 1 (stream-map add1 A))) ; easier to follow
(define C (stream-pairs A))
代替普通stream-cons
,将list
的元素与输入流的当前元素配对。现在我们有了
&GT; (for((i(in-range 0 12)))(display(stream-ref C i)))
(2 1)(3 2)(3 1)(4 3)(4 2)(4 1)(5 4)(5 3)(5 2)(5 1)(6 5)(6 4)
1 cf。,
save
答案 1 :(得分:0)
由于问题指明给定的流是无限的:
(define (stream-pairs strm)
(stream-cons (cons (stream-first strm)
(stream-first (stream-rest strm)))
(stream-pairs (stream-rest (stream-rest strm)))))
(如果流不是无限的,则需要在函数的前面添加一个空心防护。)
注意:如果您使用SRFI 41流而不是Racket流,请将define
更改为define-stream
。
答案 2 :(得分:0)
我不清楚您对“流”的意思是什么,但假设您想要这样的内容:
> (stream-subset-pairs (in-naturals) 5)
'((0 . 1) (1 . 2) (2 . 3) (3 . 4))
将其作为预期输出,这是一个解决方案:
(define (stream-subset-pairs stream i)
(define subset ; collect all elements up to i by iterating over the list and all #'s in sequence
(for/list ([element stream]
[position (in-naturals)]
#:break (= position i)) ; break when we have reached the # of elements we want to collect
element))
(let-values ([(ignore result) ; wrapper because we want for/fold to produce one result (last-element is just a state variable)
(for/fold ([last-element null]
[result empty])
([element subset]) ; iterate through the subset
(values element (if (null? last-element) ; if we are on the first loop
result ; ignore it
(cons (last-element element) result))))]) ; else add a pair of the last result and this result
result))