can read temperatures from files

This commit is contained in:
Peter Tillemans 2023-10-11 01:19:56 +02:00
parent 85d353287c
commit 27d46d5ccd
2 changed files with 38 additions and 12 deletions

View file

@ -1,19 +1,45 @@
open! Base
type t = Temperature of float
let temperature f = Temperature f
let value (Temperature f) = f
let parse s =
Stdlib.Scanf.sscanf s "%s@ t=%f" (fun _ t -> t /. 1000.)
let re = Str.regexp " t=\\([0-9]+\\)" in
try
if (Str.search_forward re s 0) > 0
then Some (Float.of_string (Str.matched_group 1 s) /. 1000.0)
else None
with Stdlib.Not_found -> None
let%test_unit "parse temperature" =
[%test_eq: float ] (parse "brol\nmore junk text t=18241") 18.241
[%test_eq: float option] (parse "brol\nmore junk text t=18241") (Some 18.241)
let read_temperature file_name =
let open Lwt.Infix in
let rec aux () =
Lwt_io.with_file ~mode:Lwt_io.Input file_name (fun ic ->
Lwt_io.read_all ic >>= function
| None -> aux ()
| Some s -> Lwt.return (parse s)
Lwt_io.read ic >>= (fun s ->
parse s |> Option.map ~f:temperature |> Lwt.return
)
in
aux
)
let write_test_file file_name =
Lwt_io.with_file ~mode:Lwt_io.Output file_name (fun oc ->
Lwt_io.write_line oc "brol\nmore junk text t=18241"
)
let%test "read temperature from file" =
let open Lwt.Infix in
let file_name = "test_temperature.txt" in
let aux = write_test_file file_name
>>= fun () -> (read_temperature file_name)
>>= function
| Some (Temperature t) -> Lwt.return Float.(t = 18.241)
| _ -> Lwt.return false
in Lwt_main.run aux

View file

@ -1,5 +1,5 @@
(library
(name oblub)
(inline_tests)
(libraries lwt lwt.unix)
(libraries str lwt lwt.unix lwt_ppx)
(preprocess (pps ppx_inline_test ppx_assert ppx_expect)))