On Stream in Scheme

(define (force delayed-object)
  (delayed-object))


(define (memo-proc proc)
  (let ((already-run? false) (result false))
    (lambda ()
      (if (not already-run?)
          (begin (set! result (proc))
                 (set! already-run? true)
                 result)
          result))))
;;(memo-proc (lambda () ))
;;(delay )
;;is syntactic sugar for 
;;(lambda () )


(define-syntax cons-stream
  (lambda (x)
    (syntax-case x ()
      ((_ a b) (syntax (cons a (delay b)))))))


(define-syntax car-stream
  (lambda (x)
    (syntax-case x ()
      ((_ s) (syntax (car s))))))


(define-syntax cdr-stream
  (lambda (x)
    (syntax-case x ()
      ((_ s) (syntax (force (cdr s)))))))


(define (for-each-stream pred s)
  (pred (car-stream s))
  (for-each-stream pred (cdr-stream s)))


(define (show-money to s)
  (call/cc (lambda (end)
             (for-each-stream (lambda (m)
                                (if (> m to)
                                    (end m))
                                (display m)
                                (newline))
                              s))))


(define (money-tree n)
  (cons-stream n (money-tree (* n n))))


(define salary (money-tree 2))




(define (sieve stream)
  (cons-stream
   (stream-car stream)
   (sieve (stream-filter
           (lambda (x)
             (not (divisible? x (stream-car stream))))
           (stream-cdr stream)))))


(define primes (sieve (integers-starting-from 2)))


Now to find a particular prime we need only ask for it: 


(stream-ref primes 50)
233

你可能感兴趣的:(stream,scheme,lambda,newline,delay)