aoc2020/bracket.ml
2020-12-06 10:13:36 +01:00

21 lines
740 B
OCaml

let bracket ~make:(lazy x) ~act ~free =
Fun.protect (fun () -> act x) ~finally:(fun () -> free x)
let infile ~act name =
bracket ~make:(lazy (open_in name)) ~act ~free:close_in_noerr
let infile_lines ~line:f ~of_seq name =
let get_line file =
try Some (f (input_line file), file)
with End_of_file -> None in
let act file = of_seq (Seq.unfold get_line file) in
infile name ~act
let infile_iter_lines ~line ~iter = infile_lines ~of_seq:(Seq.iter iter) ~line
let infile_chunks' ~chunk ~of_seq input =
let of_seq seq = Seq.line_chunks' seq |> Seq.map chunk |> of_seq in
infile_lines input ~line:Fun.id ~of_seq
let infile_chunks ?(join=" ") ~chunk =
infile_chunks' ~chunk:(fun lst -> chunk (String.concat join lst))