簡體   English   中英

無限序列方案,使無限序列

[英]infinite sequence scheme to make infinite sequence

我有一個計划中的項目,我需要實現一個無限的數字序列。 我不能使用任何方案內置的復雜函數,我只是不知道如何使序列無限,而不會導致程序在無限循環中崩潰。 我不必真正輸出它,但是我需要能夠使用它。

(seq n)   ;;output: n,n+1,n+2,n+3.... to infinity (seq 5) ->5,6,7,8,9...

現在我做了一個序列直到n + 7,但是我需要這個序列到無窮大:

(define (seq n)
   (define (asc-order LIST counter)
     (cond ((= counter (+ n 7)) LIST)
           (else (asc-order (append LIST (cons (+ counter 1) '()))  
           (+ counter 1)))))
(asc-order '() (- n 1))
)

IO示例(有效,但我需要無限序列):

>(define s (seq 3)) 
>(car s)   
3

您可以將無限序列表示為一次生成一個元素的函數。 然后,用戶(消費者)可以在每個需要序列的新元素的情況下調用該函數。

一個例子:

(define (f x) (* x x))

(define seq
  (let ()
    (define n 0)        ; current index
    (lambda ()          ; the function that is to be called repeatedly
      (define a (f n))  ;   compute the new element
      (set! n (+ n 1))  ;   compute new index
      a)))              ;   return the new element

(seq)  ; compute element 0
(seq)  ; compute element 1
(seq)  ; ...
(seq)
(seq)
(seq)

計算結果為:

0
1
4
9
16
25

為了寫(sequence->list sn)其計算所述第一n的序列元件s ,使一個循環調用s總共n倍-並收集在一個列表中的結果。

關鍵是通過在列表周圍包裝一個程序來延遲對列表的評估。

這是我能想到的最簡單的實現。
尾巴只有“懶惰”。

(define (seq n)
  (cons n (lambda () (seq (+ n 1)))))

(define (seq-car s)
  (car s))

(define (seq-cdr s)
  ((cdr s)))

使用示例:

; Get the 'n' first elements of 's'.
(define (seq-take n s)
  (if (<= n 0)
      '()
      (cons (seq-car s) (seq-take (- n 1) (seq-cdr s)))))


> (define s (seq 10))
> s
'(10 . #<procedure>)
> (seq-take 5 s)
'(10 11 12 13 14)

這是使用延遲評估的另一種解決方案:

(use-modules (ice-9 receive))


(define (seq f)
  (let loop ((n 0))
    (lambda ()
      (values (f n) (loop (1+ n))))))


(define squares (seq (lambda (x) (* x x))))

(receive (square next) (squares)
  (pk square) ;; => 0
  (receive (square next) (next)
    (pk square) ;; => 1
    (receive (square next) (next)
      (pk square) ;; => 4
      (receive (square next) (next)
        (pk square))))) ;; => 9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM