ocaml - read text file and concat lines -


i have posted few questions file io i'm trying find right 1 needs, have found , googled allot guess final file io questions (you see pseudo code here):

let ic = open_in "myfile.txt" in try   while true     let line = input_line ic in     line += "\n" + line   done end_of_file -> close_in ic;  print_endline line;; 

i have tried string.concat "\n" (line; line) it's invalid im unsure in situation how use string.concat method.

string concatenation inadequate in situation because str1 ^ str2 takes time , memory linear in sum of sizes, iterated concatenation exhibit quadratic behavior -- want avoid that.

there several solutions problem:

  1. use buffer module precisely designed accumulate strings
  2. collect lines in list of lines, , concatenate them in 1 go efficient string.concat : string -> string list -> string function (documentation).
  3. use existing library you. example, batteries has input_all function whole content of input channel file.

.

let read_file file =   let ic = open_in file in   let buf = buffer.create (in_channel_length ic) in   try     while true       let line = input_line ic in       buffer.add_string buf line;       buffer.add_char buf '\n';     done; assert false   end_of_file ->     buffer.contents buf ;;  let read_file file =   let ic = open_in file in   let lines = ref [] in   try     while true       let line = input_line ic in       lines := line :: !lines     done; assert false   end_of_file ->     string.concat "\n" !lines  let test = read_file "blah.ml" 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -