aoc2020/bracket.ml

22 lines
740 B
OCaml
Raw Normal View History

2020-12-02 06:05:38 -05:00
let bracket ~make:(lazy x) ~act ~free =
2020-12-03 10:49:28 -05:00
Fun.protect (fun () -> act x) ~finally:(fun () -> free x)
2020-12-02 04:31:32 -05:00
let infile ~act name =
2020-12-02 06:05:38 -05:00
bracket ~make:(lazy (open_in name)) ~act ~free:close_in_noerr
2020-12-02 04:31:32 -05:00
let infile_lines ~line:f ~of_seq name =
let get_line file =
2020-12-02 06:05:38 -05:00
try Some (f (input_line file), file)
with End_of_file -> None in
2020-12-02 04:31:32 -05:00
let act file = of_seq (Seq.unfold get_line file) in
infile name ~act
2020-12-02 06:05:38 -05:00
let infile_iter_lines ~line ~iter = infile_lines ~of_seq:(Seq.iter iter) ~line
2020-12-06 03:11:35 -05:00
2020-12-06 04:13:36 -05:00
let infile_chunks' ~chunk ~of_seq input =
let of_seq seq = Seq.line_chunks' seq |> Seq.map chunk |> of_seq in
2020-12-06 03:11:35 -05:00
infile_lines input ~line:Fun.id ~of_seq
2020-12-06 04:13:36 -05:00
let infile_chunks ?(join=" ") ~chunk =
infile_chunks' ~chunk:(fun lst -> chunk (String.concat join lst))