[plt-scheme] static variable redux

From: Hugh Myers (hsmyers at gmail.com)
Date: Wed Jul 1 22:23:20 EDT 2009

Here is what I came up with after wandering through a thicket of
docs(thanks all!):

> (define (make-counter [start 0])
  ;; A re-setable counter.
  (define (next)
    (incf! start)
    start)
  (define (reset)
    (set! start 0))
  (define (dispatch [m 'next])
    (cond
      ((eq? m 'next) next)
      ((eq? m 'reset) reset)
      (else (error "unknown request in counter:" m))))
  dispatch)
> (define counter (make-counter))
> ((counter))
1
> ((counter))
2
> ((counter 'reset))
> ((counter))
1

Oops, pardon the incf!--- a macro:

(define-syntax incf!
;; stolen from CL
  (λ (stx)
    (syntax-case stx ()
      [(incf! n)
       (if (identifier? #'n)
           #'(set! n (+ 1 n))
           (raise-syntax-error #f
                               "not an identifier"
                               stx
                               #'n))])))

--hsm


Posted on the users mailing list.