samuel jie
samuel jie

Reputation: 17

If statements questions in OCaml

I am trying to write the following code in OCaml:

let a = 0
let b = 1 

if a > b then 
  {
    print_endline "a";
    print_endline "a";
  }
print_endline "b"

And then I encountered the following error:

File "[21]", line 4, characters 0-2:
4 | if a > b then 
    ^^
Error: Syntax error

I have tried using the begin and end keywords.

Upvotes: 0

Views: 112

Answers (1)

Chris
Chris

Reputation: 36451

If you're writing a program (rather than mucking about in a REPL), then there are only certain constructs which can exist at the top level of your program.

One of those is a binding. So the following is fine:

let a = 0
let b = 1 

But a conditional expression (if/else) is not permitted; nor are any other bare expressions, which include local bindings (let ... in ...). We can get around this by binding that expression to a pattern. Since print_endline will just return (), we can write:

let () =
  ...

Your use of { and } is incorrect in this situation, but you can group multiple expressions with ; and ( and ). Remember that ; is not a "statement terminator" but rather a separator.

let () =
  if a > b then (
    print_endline "a";
    print_endline "a"
  );
  print_endline "b"

Alternatively you can use begin and end instead of parentheses.

let () =
  if a > b then begin
    print_endline "a";
    print_endline "a"
  end;
  print_endline "b"

Note that if can only exist without a matching else if the entire expression returns unit. This meets that criteria.

Upvotes: 6

Related Questions