Home > Enterprise >  How to store a list in a file with Print.f in OCaml
How to store a list in a file with Print.f in OCaml

Time:07-04

I aim to write a function to read a string list persons with open_out and store it in the file filename I tried to iterate over it with List.fold_left and use Print.f, however it is not working.

let write_list filename persons =
  let file = open_out filename in 
  let write_person p =
    let rec ite_pres aux acc = List.fold_left (Printf.fprintf file "%s\n" filename )
    List.iter write_person persons;
  close_out 

CodePudding user response:

Since you want to print one line by file List.iter is enough:

let chan = 
List.iter (Printf.fprintf chan "%s\n") persons

With OCaml 4.14 and later version, you can also use with_open_text which opens and close the file channel by itself:

let write_list filename persons =
  Out_channel.with_open_text filename (fun chan ->
    List.iter (Printf.fprintf chan "%s\n") persons
  )

with_

CodePudding user response:

You don't need to mess with folds, or even with the Printf module, if all you want to do is write a string list to a file, one element per line. For example:

(* Like print_endline but for arbitrary output channels *)
let output_endline chan s = output_string chan s; output_char chan '\n'

(* Open a file and call f with the output channel as its argument.
 * Note: Available as Out_channel.with_open_text in Ocaml 4.14 and newer *)
let with_open_text filename f =
  let chan = open_out filename in
  try
    f chan; close_out chan
  with x -> close_out chan; raise x

let print_list_to_file filename slst =
  with_open_text filename (function chan -> List.iter (output_endline chan) slst)

let _ = print_list_to_file "output.txt" ["a";"b";"c"]

This defines a couple of handy convenience functions, and uses with them List.iter to print out the list.

  • Related