Reputation: 1669
In the ocaml-containers
documentation, it gives a great example, how to read in a file, and write the content to a different file here. However, I am trying to see what it would take to modify the text before it is passed from the file being read to file being written.
let read_filename = "example.ts"
let filename = "example2.ts"
let () =
let modify_file ~chunks =
let r = Str.regexp "text \\([A-Za-z]+\\)" in
Str.replace_first r "\\1" chunks in
CCIO.(
with_in read_filename
(fun ic ->
let chunks = read_chunks ic in
let new_chunks = modify_file chunks in
with_out ~flags:[Open_binary] ~mode:0o644 filename
(fun oc ->
write_gen oc new_chunks
)
)
)
The issue with this code, is that the compiler complains:
File "component.ml", line 13, characters 39-45:
Error: This expression has type string gen = unit -> string option
but an expression was expected of type string
I am trying to figure out what I am doing wrong, but to no avail. Any help would be more than appreciated. Also, suggestions as to the ideal enterprise software to use in OCaml to modify text in files, is more than appreciated. Thank you.
Upvotes: 0
Views: 79
Reputation: 629
You have a typing problem
read_chunk ic
return a string gen
value
from here we learn that is a function that take unit value ()
and return a string.
let () =
CCIO.(
let modify_file ~chunks =
let r = Str.regexp "example \\([A-Za-z]+\\)" in
match chunks () with
None -> chunks (* is the same as (fun () -> None) *)
| Some chunks ->
let chunks = Str.replace_first r "\\1" chunks in (* compute once *)
(fun () -> Some chunks) in
with_in read_filename
(fun ic ->
let chunks = read_chunks ic in
let new_chunks = modify_file ~chunks in
with_out ~flags:[Open_binary] ~mode:0o644 filename
(fun oc ->
write_gen oc new_chunks
)
)
)
EDIT: explain the error and the change
EDIT 2: I have modifier modify_file so it return antoher string gen and corrected the syntax error: when you use labeled argument you need to add a tilde when calling it
Upvotes: 1
Reputation: 629
What is the type of modify_file
. I don't see it in the manual.
You should try to add unit value ()
this way
let new_chunks = modify_file chunks () in
and new_chunks
will be of type string option
You can pattern match as option type.
EDIT:
I have seen that third parameter has type string gen
You should modify the 16th line this way:
write_gen oc (fun () -> new_chunks)
Upvotes: 0