vent
vent

Reputation: 39

Simple ocaml code didn't work

I have a simple code in Ocaml described below:

for i = 1 to 9 do
  for j = 1 to 9 do
    let k = i*10+j
    Format. printf "(define x%d :: int)@." k
  done;
  print_newline ()
done

But it results in a syntax error, and I don't know why:

File "main.ml", line 5, characters 2-6: Error: Syntax error --> Line 5: done;

Please help me fix it and recommend me a good book to learn Ocaml. I am a newbie, so confused about everything in it. Ocaml is completely different with C++.

Thank you so much

Upvotes: 0

Views: 80

Answers (1)

ivg
ivg

Reputation: 35210

you have forgotten in on the third line.

You can find a lot of sources about OCaml, including good books here.

Update

for i = 1 to 9 do
  for j = 1 to 9 do
    let k = i * 10 + j in (* <- syntax requires you to put `in` here *)
    Format.printf "(define x%d :: int)@." k
  done;
  print_newline ()
done

There are two kinds of let bindings in OCaml:

  1. toplevel binding, that can occur inside the module definitions and toplevel, it has a form of let <name> = <expr>
  2. expression binding, that can occur inside other expressions, including functions, it has form of let <name> = <expr-1> in <expr-2>, and it creates a binding between <name> and <expr-1> that works in the scope of <expr-2>, where binding is an association between a name and a value, and scope is a lexical part of code (i.e., part of code that is occupied by <expr-2>).

Anyway, it is hard to explain OCaml in two sentences, so consider reading OCaml books, that are written by much more experienced teachers, than I am))

Upvotes: 3

Related Questions