Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I suggest defining a simple helper function, <code>make-codec-input-port</code>, that lets you create an input-port from an original input-port and a "codec" function. The key point here -- which wasn't obvious to me from the Racket documentation for <code>make-pipe</code> -- is that you want to run a <code>thread</code> that calls the codec function.</p> <p>Here I show a trivial codec that replaces every <code>#\a</code> character with <code>#\b</code>. You could change its <code>match</code> statement to do something more interesting.</p> <pre><code>#lang racket ;; Given an input-port and a codec function, return a new input-port ;; that is the encoded version. `codec` is (input-port? output-port? ;; -&gt; any). For example can be deflate, inflate, gzip-through-ports, ;; gunzip-through-ports, copy-port (the identity function for this), ;; or your own such function. (define codec-buffer-size (make-parameter 1024)) (define (make-codec-input-port in codec [name #f]) (define-values (pin pout) (make-pipe (codec-buffer-size) name name)) (thread (lambda () (codec in pout) (close-output-port pout))) pin) ;; Example of a codec function. (define (replace-a-with-b in out) ;; (input-port? output-port? -&gt; any) (let loop () (define ch (read-char in)) (unless (eof-object? ch) (write-char (match ch [#\a #\b] [x x]) out) (loop)))) ;; You could also write the codec function a bit more simply using ;; `in-port`: (define (replace-a-with-b in out) ;; (input-port? output-port? -&gt; any) (for ([ch (in-port read-char in)]) (write-char (match ch [#\a #\b] [x x]) out))) ;; Example direct use of the codec function. (let () (define orig-in (open-input-string "axaxax")) (replace-a-with-b orig-in (current-output-port))) ;; =&gt; bxbxbx ;; Example use of the encoded input port. With this, a user of the ;; port need not know anything about the codec function. (let () (define orig-in (open-input-string "axaxax")) (define encoded-in (make-codec-input-port orig-in replace-a-with-b)) (port-&gt;string encoded-in)) ;; =&gt; "bxbxbx" </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload