[plt-scheme] writing scheme application extensions in scheme

From: Paul Graunke (ptg at ccs.neu.edu)
Date: Mon Jun 9 23:36:24 EDT 2003

On Monday, June 9, 2003, at 05:16 PM, Peter Santoro wrote:
> ;------------------------------------
> ; sample hook-mgr.scm
>
> (define _hooks (list))
(define _hooks empty)
; or
(define _hooks null)
; work, too.

> (define _hook-key 0)

;If you only need to compare keys for eq?-ness (i.e. you don't need to 
multiply, add,
;subtract, etc the keys) then you might want to use symbols instead.
;Then you can eliminate _hook-key.
>
> (define (get-next-hook-key)
>   (begin0 _hook-key (set! _hook-key (+ _hook-key 1))))

(gensym) ; generates a new, unique symbol

(define (get-next-hook-key)
   (set! _hook-key (add1 _hook-key))
   _hook-key)
; will work if you are stuck with numbers

>
> (define (get-hook-key ls)
>   (car ls))
>
> (define (get-hook-desc key)
>   (let ((ls (assq key _hooks)))
>     (if ls
>       (caadr ls)
>       #f)))
>
> (define (get-hook-proc key)
>   (let ((ls (assq key _hooks)))
>     (if ls
>       (cadadr ls)
>       #f)))
>
> (define (set-hook! proc menu-text)
>   (set! _hooks (append _hooks (list (list (get-next-hook-key) (list 
> menu-text proc))))))
>

;You might want to use a hash table with symbols for keys.  Search 
help-desk.

;Use structures instead of lists when you know how many pieces there 
are.
(define-struct extension (menu-text proc))
; Then replace
(list some-menu-text some-proc)
; with
(make-extension some-menu-text some-proc)
; You can retrieve the pieces
(extension-menu-text (make-extension x f)) = x
(extension-proc (make-extension x f)) = f
; and recognize extensions
(extension? (make-extension x f)) = #t
(extension? 5) = #f

Also, if you are trying to keep _hooks private by starting the name 
with an _, you
should search help-desk for "module" .  They can hide private variables 
like _hooks.
(I would then drop the underscore.)

Enjoy!

Paul



Posted on the users mailing list.