Do Racket streams memoize their elements?

孤街醉人 提交于 2019-12-04 09:22:53

The built-in racket/stream library uses lazy evaluation and memoization to draw elements from a stream:

(require racket/stream)

(define (print-and-return x)
  (displayln "drawing element...")
  x)

(define (in-range-stream n m)
  (if (= n m)
      empty-stream
      (stream-cons (print-and-return n) (in-range-stream (add1 n) m))))

(define s (in-range-stream 5 10))

(stream-first s)
(stream-first s)
(stream-first (stream-rest s))

The expressions passed to stream-cons are not evaluated until requested either with stream-first or stream-rest. Once evaluated, they are memoized. Notice that despite the four stream operations performed on s, only two `"drawing element..." messages are displayed.

You can use the memoize package.

GitHub source: https://github.com/jbclements/memoize/tree/master

raco pkg install memoize

Using it is as simple as replacing define with define/memo. To quote its example:

(define (fib n)                                     
  (if (<= n 1) 1 (+ (fib (- n 1)) (fib (- n 2)))))  

> (time (fib 35))                                   
cpu time: 513 real time: 522 gc time: 0             
14930352                                            

> (define/memo (fib n)                              
    (if (<= n 1) 1 (+ (fib (- n 1)) (fib (- n 2)))))

> (time (fib 35))                                   
cpu time: 0 real time: 0 gc time: 0                 
14930352      

Also, it is generally quite easy to implement memoization yourself using a Racket hash-table.

For other Scheme implementations that use SRFI 41 streams, those streams also fully memoise all the materialised elements.

In fact, in my Guile port of SRFI 41 (which has been in Guile since 2.0.9), the default printer for streams will print out all the elements so materialised (and nothing that isn't):

scheme@(guile-user)> ,use (srfi srfi-41)
scheme@(guile-user)> (define str (stream-from 0))
scheme@(guile-user)> (stream-ref str 4)
$1 = 4
scheme@(guile-user)> str
$2 = #<stream ? ? ? ? 4 ...>

Any of the elements that aren't being printed out as ? or ... have already been memoised and won't be recomputed. (If you're curious about how to implement such a printer, here's the Guile version.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!