[racket] Read-only parameters

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Mon Feb 11 22:36:30 EST 2013

I don't think there's currently a way to have a read-only parameter.

If you know when you're calling a function that might mutate a
parameter, then you can constrain mutation to the dynamic extent of the
call by wrapping the call with a `parameterize'. The `limit' wrapper
below does that.

----------------------------------------

#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)
  (parameterize ([my-curr-out-port (open-output-nowhere)])
  (hello)))

(define (mute)
  (my-curr-out-port (open-output-nowhere))) ; I'd want an error here.

;; constrain any mutation of `my-cur-out-port' to the dynamic
;; extent of `thunk':
(define (limit thunk)
  (parameterize ([my-curr-out-port (my-curr-out-port)])
    (thunk)))

(hello) ;---> "Hello"
(limit quietly) ;---> ""
(hello) ;---> "Hello"
(limit mute)
(hello) ;---> "Hello" :)



Posted on the users mailing list.