can read temperatures from files
This commit is contained in:
parent
85d353287c
commit
27d46d5ccd
2 changed files with 38 additions and 12 deletions
|
@ -1,19 +1,45 @@
|
||||||
open! Base
|
open! Base
|
||||||
|
|
||||||
let parse s =
|
type t = Temperature of float
|
||||||
Stdlib.Scanf.sscanf s "%s@ t=%f" (fun _ t -> t /. 1000.)
|
|
||||||
|
let temperature f = Temperature f
|
||||||
|
|
||||||
let%test_unit "parse temperature" =
|
let value (Temperature f) = f
|
||||||
[%test_eq: float ] (parse "brol\nmore junk text t=18241") 18.241
|
|
||||||
|
let parse s =
|
||||||
|
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 option] (parse "brol\nmore junk text t=18241") (Some 18.241)
|
||||||
|
|
||||||
|
|
||||||
let read_temperature file_name =
|
let read_temperature file_name =
|
||||||
let open Lwt.Infix in
|
let open Lwt.Infix in
|
||||||
let rec aux () =
|
Lwt_io.with_file ~mode:Lwt_io.Input file_name (fun ic ->
|
||||||
Lwt_io.with_file ~mode:Lwt_io.Input file_name (fun ic ->
|
Lwt_io.read ic >>= (fun s ->
|
||||||
Lwt_io.read_all ic >>= function
|
parse s |> Option.map ~f:temperature |> Lwt.return
|
||||||
| None -> aux ()
|
|
||||||
| Some s -> Lwt.return (parse s)
|
|
||||||
)
|
)
|
||||||
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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
2
lib/dune
2
lib/dune
|
@ -1,5 +1,5 @@
|
||||||
(library
|
(library
|
||||||
(name oblub)
|
(name oblub)
|
||||||
(inline_tests)
|
(inline_tests)
|
||||||
(libraries lwt lwt.unix)
|
(libraries str lwt lwt.unix lwt_ppx)
|
||||||
(preprocess (pps ppx_inline_test ppx_assert ppx_expect)))
|
(preprocess (pps ppx_inline_test ppx_assert ppx_expect)))
|
||||||
|
|
Loading…
Reference in a new issue