[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: dynamic-wind
From: |
Panicz Maciej Godek |
Subject: |
Re: dynamic-wind |
Date: |
Fri, 30 Jun 2017 23:48:23 +0200 |
2017-06-30 22:33 GMT+02:00 Catonano <address@hidden>:
> On the irc channel I was suggested that it might have been a good fit for
> my use case
>
> I took a look at it in the manual
>
> I'm perplexed. I don't understand it
>
> How is it supposed to be used ?
>
>
It's very simple (at least from the point of view of a user)
When it is tempting to write something like
(define (within-context action)
(enter-context)
(action)
(leave-context))
you simply change it to
(define (within-context action)
(dynamic-wind
(lambda () (enter-context))
action
(lambda () (leave-context))))
The thing is, that in general (action) may transfer control outside of the
scope of that particular context (like, using call/cc or exceptions) -- and
in such situations, we would like the (leave-context) handler to be
invoked. If and we ever get back there, we wish that the (enter-context)
were invoked again.
> The provided example is somewhat contrived, I couldn't understand it
> anyway.
>
> My use case is basic, really.
>
> I have a scheme wrap around a C library for reading xls files, freexl.
>
> Freexl uses a pointer to a structure tha represents the opened xls file and
> its contents
>
> Each function writes/reads in the memory region pointed to such pointer.
>
> In the end, it requires to use a function that closes the file AND frees
> all the involved structures in memory.
>
> So my idea was that I would have gotten a simple macro, like this
>
> (with-xls-file "path/to/my/xls-file.xls" handler-ptr
> (do-something handler-ptr)
> (do-something-more handler-ptr))
>
> and this would have expanded to
>
> (freexl-open "path/to/my/xls-file.xls" handler-ptr)
> (freexl-do-something handler-ptr)
> (freexl-do-something-more handler-ptr))
> (freexl-close handler-ptr)
>
> Do I need dynamic-wind at all ?
>
If you don't use dynamic-wind, some of the possible use cases will not be
covered. Non-local transfers of control will break the system.
I believe you'd like to assume that there shouldn't be any non-local
transfers of control, but actually you can't know this. And the interface
to dynamic-wind is very straightforward, so there's no excuse for not using
it.
Here's a simple real life example in Scheme:
(define current-working-directory getcwd)(define change-directory chdir)
(define (with-changed-working-directory dir thunk) (let ((cwd
(current-working-directory))) (dynamic-wind (lambda ()
(change-directory dir)) thunk (lambda () (change-directory
cwd)))))
HTH
- dynamic-wind, Catonano, 2017/06/30
- Re: dynamic-wind,
Panicz Maciej Godek <=