poudandane
poudandane

Reputation: 9

OCaml initializing list in loop for

I am a beginner with OCaml. I would like to skip the first element of my list.

Here is my list:

let l = [1;2;3;4;5;6;7;2;1];;

I want to use this in my FOR:

let l = List.tl l;

here is my full code:

let l = [1;2;3;4;5;6;7;2;1];;
let n = 1;;
let counter = ref 0;;
for i = 0 to (List.length l) do
if List.hd l = n then counter := !counter + 1;
print_int(!counter);
print_string("\n");
let l = List.tl l
done;;

But I have errors in the DONE and it says syntax error.

Can anyone help me please?

Upvotes: 0

Views: 168

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

Your problem is that let always requires a matching in. The full expression looks like this:

let var = expr1 in expr2

Since you're missing the in part, you get a syntax error.

However, the deeper problem is that you're trying to modify the value of l. The way you have defined l, it's immutable. You can't change its value. If you want to be able to change its value you can define it as a reference, as you have done for counter.

(There is another form of let used at the top level of a module. This form doesn't have a matching in. But your code isn't defining a top-level name, so this is not relevant.)

Upvotes: 1

Related Questions