Reputation: 31
I'm begining my learning of OCaml and I have been quite stuck on a simple problem. I'm trying to count with a simple loop the number of letters that I have in a file of 6 lines. Here's my code :
let fi = open_in "example";;
let string = "";;
let nb_carac = 0;;
for i = 0 to 6 do
string = input_line fi;
nb_carac = (nb_carac + String.length(string));
done;;
Problem is, it doesn't seem to count anything and reaches directly to EOF
.
I get the following error message:
Warning 10: this expression should have type unit.
Warning 10: this expression should have type unit.
Exception: End_of_file.
I don't really get it. I have tried each line individually and they all worked. What am i doing wrong?
Thanks!
Upvotes: 1
Views: 2472
Reputation: 1
OCaml does not have mutable variables. You should use tail recursion or references. Read any basic OCaml textbook or tutorial.
Both lines:
string = input_line fi;
nb_carac = (nb_carac + String.length(string));
are understood as useless equality tests (this explains the warning you are getting).
Perhaps you want:
(* shameful *)
let string = ref "";;
let nb_carac = ref 0;;
then e.g.
(* shameful *)
string := input_line fi;
nb_carac := !nb_carac + String.length(!string);
but you should get a very bad grade if you code so imperatively in a functional language like OCaml.
As a rule of thumb, avoid mutating data when coding in OCaml. Of course there are important exceptions to this rule.
The correct solution to your exercise is to use tail recursive functions which do not mutate any data. Look at OCaml standard library stdlib/list.ml for some inspiration.
Probably a better solution to your exercise starts with
let count_lines_and_characters fil = (* incomplete code, fill the ... *)
let rec ....
in ....
;;
Of course you should fill the ....
Upvotes: 2