March 22th Thursday (三月 二十二日 木曜日)

来源:互联网 发布:网络交换器什么牌子好 编辑:程序博客网 时间:2024/03/29 09:33

  (define dynamic-wind
    (lambda (before thunk after)
      (before)
      (call-with-values
        (lambda () (thunk))
          (lambda vals
            (after)
            (apply values vals)))))

  That is, before is called without arguments.  If before returns, thunk is called without arguments.
If thunk returns, after is called without arguments.  Finally, if after returns, the values resulting
from the call to thunk are returned.

  Invoking an escape procedure to transfer control into or out of the dynamic extent of the call to
thunk can cause additional calls to before and after.  When an escape procedure created outside the dynamic extent of the call to thunk is invoked from within the dynamic extent, after is called just
after control leaves the dynamic extent.  Similarly, when an escape procedure created within the
dynamic extent of the call to thunk is invoked from outside the dynamic extent, before is called just
before control reenters the dynamic extent.  In the latter case, if thunk returns, after is called
even if thunk has returned previously.  While the calls to "before" and "after" are not considered to
be within the dynamic extent of the call to thunk, calls to the before and after thunks of any other calls to "dynamic-wind" that occur within the dynamic extent of the call to thunk are considered to be
within the dynamic extent of the call to thunk.

  The above description is so complicated.  There is example.  You can typed it and run.  Whan happed?

  (define ck #f)
  (+ 1 (call/cc (lambda (k) (set! ck k) 2)) 3)
  => 6

  This is the first run.  OK. Enter the following codes at your scheme interpretor.

  (ck 9)
  => 13

  Now you ought to understand the nature of "dynamic-wind".  The "dynamic-wind" is just used to
maintain a sequence of calls for procedures.  Its implementation does not use "call/cc" though there
is current continuation behind scene.  It is so simple, so inituitive.  When we call a current continuation, our program flow jump back a original location at where that continuation is born.  The
location is a "break point", the sequence of express where the "break point" will evaluated again.

  More example can be used to understand current continuation.

  (+ (call/cc (lambda (x) (x 2) 3)) 4) => 6