(Lispex)sicp.io
3.4 · 시간을 수열로 나타내기

스트림은 요구한 부분만 드러낸다.

스트림은 지금의 첫 값을 보관하고 나머지 수열을 만드는 계산은 지연합니다.

생각해 볼 질문

끝이 없는 수열을 유한한 실행에서 어떻게 사용할 수 있을까요?

  • Read a stream as a present value and a delayed tail
  • Follow demand through repeated stream-ref calls
  • Distinguish describing an infinite process from executing forever

integers-from can describe an unending sequence because cons-stream does not evaluate its tail immediately. Each tail is a promise for the next pair.

stream-ref forces exactly as many tails as it needs to reach the requested index. Asking for index 9 constructs a finite prefix and returns 10, so this particular run terminates.

리스펙스 · SICP 코드SICP에 필요한 Scheme 호환 문법을 리스펙스 SICP 프로필로 실행합니다.
(letrec ((integers-from
          (lambda (n)
            (cons-stream n (integers-from (+ n 1)))))
         (stream-ref
          (lambda (stream n)
            (if (= n 0)
                (car stream)
                (stream-ref (force (cdr stream)) (- n 1))))))
  (stream-ref (integers-from 1) 9))
리스펙스 학습용 런타임리스펙스 SICP 프로필 1.0.0
리스펙스 SICP 런타임 불러오는 중
리스펙스 · SICP 코드UTF-8 300 / 1,048,576바이트
예제
결과
출력
진단
보이는 실행 흐름0 / 0 개의 실행 이벤트
    이 브라우저 결과는 리스펙스 바우치나 권한이 아닙니다.wasm —
    예상 관찰

    The first program returns 10 after forcing nine stream tails.

    실행 흐름에서 볼 점

    Find the repeated force events. Each computed outcome exposes one more pair, while the unrequested remainder stays delayed.

    직접 해보기

    힌트를 보기 전에 프로그램을 바꿔 보세요.

    Change the requested index from 9 to 4. Predict the value and how many stream tails must be forced.

    힌트 하나 보기

    Index 0 uses the current car without forcing the cdr.