|
| 1 | +(* |
| 2 | +Copyright (c) 2015, KC Sivaramakrishnan <[email protected]> |
| 3 | +
|
| 4 | +Permission to use, copy, modify, and/or distribute this software for any |
| 5 | +purpose with or without fee is hereby granted, provided that the above |
| 6 | +copyright notice and this permission notice appear in all copies. |
| 7 | +
|
| 8 | +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 9 | +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 10 | +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 11 | +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 12 | +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 13 | +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 14 | +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 15 | +*) |
| 16 | + |
| 17 | +(* User-land dynamic wind: |
| 18 | + http://okmij.org/ftp/continuations/implementations.html#dynamic-wind *) |
| 19 | +open Effect |
| 20 | +open Effect.Deep |
| 21 | + |
| 22 | +let dynamic_wind before_thunk thunk after_thunk = |
| 23 | + before_thunk (); |
| 24 | + let res = |
| 25 | + match_with |
| 26 | + thunk |
| 27 | + () |
| 28 | + { retc = Fun.id |
| 29 | + ; exnc = |
| 30 | + (fun e -> |
| 31 | + after_thunk (); |
| 32 | + raise e) |
| 33 | + ; effc = |
| 34 | + (fun (type a) (e : a Effect.t) -> |
| 35 | + Some |
| 36 | + (fun (k : (a, _) continuation) -> |
| 37 | + after_thunk (); |
| 38 | + let res' = perform e in |
| 39 | + before_thunk (); |
| 40 | + continue k res')) |
| 41 | + } |
| 42 | + in |
| 43 | + after_thunk (); |
| 44 | + res |
| 45 | + |
| 46 | +type _ Effect.t += E : unit Effect.t |
| 47 | + |
| 48 | +let () = |
| 49 | + let bt () = Printf.printf "IN\n" in |
| 50 | + let at () = Printf.printf "OUT\n" in |
| 51 | + let foo () = |
| 52 | + Printf.printf "peform E\n"; |
| 53 | + perform E; |
| 54 | + Printf.printf "peform E\n"; |
| 55 | + perform E; |
| 56 | + Printf.printf "done\n" |
| 57 | + in |
| 58 | + try_with |
| 59 | + (dynamic_wind bt foo) |
| 60 | + at |
| 61 | + { effc = |
| 62 | + (fun (type a) (e : a Effect.t) -> |
| 63 | + match e with |
| 64 | + | E -> |
| 65 | + Some |
| 66 | + (fun (k : (a, _) continuation) -> |
| 67 | + Printf.printf "handled E\n"; |
| 68 | + continue k ()) |
| 69 | + | _ -> None) |
| 70 | + } |
0 commit comments