[plt-scheme] ports and garbage collection
On Mon, 22 Nov 2004 04:48:24 +0900, Daniel Silva <daniel.silva at gmail.com> wrote:
> It doesn't have to be ugly :-)
> ...
Sorry, the code I posted was actually pretty ugly! I shouldn't have
used 'define' in the macro and I shouldn't rewrite dynamic-wind. So:
(module call-with-resource mzscheme
(require (lib "contract.ss"))
(define (call-with-resource res use-res shutdown-res)
(dynamic-wind void
(lambda ()
(use-res res))
(lambda ()
(shutdown-res res))))
;; this contract is awful... what's the right way to have the
properties/types flow?
(provide/contract [call-with-resource (any/c
(any/c . -> . any/c)
(any/c . -> . any/c)
. -> .
any/c)]))
(module using-port-fn mzscheme
(require (lib "contract.ss"))
(require "call-with-resource.ss")
(define (using-port port proc)
(call-with-resource port
(lambda (p)
(parameterize ([current-input-port p])
(proc)))
close-input-port))
(provide/contract [using-port (input-port? (-> any/c) . -> . any/c)]))
(module with-resource mzscheme
(define-syntax (with-resource stx)
(syntax-case stx ()
[(_ (res-id res-expr shutdown-proc) exprs ...)
(identifier? (syntax res-id))
#`(let ([res-id res-expr])
(dynamic-wind void
(lambda ()
exprs ...)
(lambda ()
(shutdown-proc res-id))))]))
(provide with-resource))
(module using-port-stx mzscheme
(require "with-resource.ss")
(define-syntax (using-port stx)
(syntax-case stx ()
[(_ port exprs ...)
#`(with-resource (p port close-input-port)
(parameterize ([current-input-port p])
exprs ...))]))
(provide using-port))
Daniel