Advertisement
kenpusney

effekt.ml

May 17th, 2023 (edited)
1,833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.77 KB | None | 0 0
  1. open Effect
  2. open Effect.Shallow
  3.  
  4. type 'a t += Recur : 'a -> 'b t
  5.  
  6. let recur a = perform (Recur a)
  7.  
  8. let loop : 'a -> ('a -> 'b) -> 'b =
  9.  fun init fn ->
  10.   let rec run : ('a, 'b) continuation -> 'a -> 'b =
  11.    fun k input ->
  12.     continue_with k input
  13.       {
  14.         retc = (fun x -> x);
  15.         exnc = (fun e -> raise e);
  16.         effc =
  17.           (fun (type b) (eff : b t) ->
  18.             match eff with
  19.             | Recur value ->
  20.                 Some
  21.                   (fun (_ : (b, _) continuation) ->
  22.                     run (fiber fn) (Obj.magic value))
  23.             | _ -> None);
  24.       }
  25.   in
  26.   run (fiber fn) init
  27.  
  28. let fact i =
  29.   loop (i, 1) (fun (iter, acc) ->
  30.       if iter > 0 then recur (iter - 1, iter * acc, 1) else acc)
  31.  
  32. let () = print_int (fact 10)
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement