From f6db3535b39e1c1dd0ce30f5e90b637871a45fae Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 15 Feb 2022 21:27:06 -0500 Subject: [PATCH] add fib.exe example --- dune | 4 ++-- fib.ml | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 fib.ml diff --git a/dune b/dune index e18232f64..88809917d 100644 --- a/dune +++ b/dune @@ -1,4 +1,4 @@ -(executable - (name test) +(executables + (names test fib) (libraries lwt lwt.unix)) diff --git a/fib.ml b/fib.ml new file mode 100644 index 000000000..6e43941b7 --- /dev/null +++ b/fib.ml @@ -0,0 +1,27 @@ + +open Lwt.Syntax + +let suspend f = + let* () = Lwt.pause() in + f() + +let rec sleepy_fib n = + if n <= 2 then ( + Lwt.await @@ Lwt_unix.sleep 0.2; + Lwt.return 1 + ) else ( + let f1 = sleepy_fib (n-1) in + let f2 = sleepy_fib (n-2) in + Lwt.await @@ Lwt_unix.sleep 0.2; + let res = Lwt.await f1 + Lwt.await f2 in + Printf.printf "fib %d = %d\n%!" n res; + Lwt.return res + ) + +let main () = + suspend @@ fun () -> + let _res = Lwt.await @@ sleepy_fib 10 in + Lwt.return() + +let () = + Lwt_main.run @@ main ()