[racket] Read-only parameters

From: Neil Toronto (neil.toronto at gmail.com)
Date: Mon Feb 11 18:32:45 EST 2013

On 02/11/2013 04:04 PM, Gustavo Massaccesi wrote:
> I was trying to define a "read-only" parameter, i.e. a parameter that
> can be "read" and "parameterized", but not "written". I'd want to call
> functions without being worried that the any of them changes that
> parameter, but I want to allow each function to parameterize the
> parameter for internal use.
>
> Perhaps an "example" is clearer:
> ;-----
> #lang racket/base
> (require racket/port)
>
> (define my-curr-out-port (make-parameter (current-output-port)))
>
> (define (hello)
>    (displayln "Hello" (my-curr-out-port)))
>
> (define (quietly)>
> Gustavo
> ____________________
>    Racket Users list:
>    http://lists.racket-lang.org/users
>

>    (parameterize ([my-curr-out-port (open-output-nowhere)])
>    (hello)))
>
> (define (mute)
>    (my-curr-out-port (open-output-nowhere))) ; I'd want an error here.
>
> (hello) ;---> "Hello"
> (quietly) ;---> ""
> (hello) ;---> "Hello"
> (mute)
> (hello) ;---> "" :(
> ;---

If you don't mind having a special form to parameterize 
`my-curr-out-port', you can do it with a macro.


#lang racket/base

(module defs racket/base
   (require racket/port)

   (provide my-curr-out-port with-my-curr-out-port)

   (define my-curr-out-port* (make-parameter (current-output-port)))

   (define (my-curr-out-port) (my-curr-out-port*))

   (define-syntax-rule (with-my-curr-out-port port  . body)
     (parameterize ([my-curr-out-port*  port])
       . body)))

(require (submod "." defs)
          racket/port)

(define (hello)
   (displayln "Hello" (my-curr-out-port)))

(define (quietly)
   (with-my-curr-out-port (open-output-nowhere)
     (hello)))

(define (mute)
   (my-curr-out-port (open-output-nowhere)))

(hello)    ;---> "Hello"
(quietly)  ; prints nothing
(hello)    ;---> "Hello"
(mute)     ; error here


Neil ⊥


Posted on the users mailing list.