snctmpst
snctmpst

Reputation: 145

OCaml- local variables in if-else block?

How would you make a local variable within an if-else block? (if that's valid in Ocaml)

Here's example code in C of what I'm trying to do in OCaml:

if (1 == 1) {
        return 3;
    } else {
        int j = 5;
        return j;
    }

Upvotes: 1

Views: 1184

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

You have to realize that variables in OCaml are immutable, i.e., they are bound to a value when declared, and the value is never changed.

If you're comfortable with this meaning of "variable", then you can declare local variables anywhere an expression can appear. An expression of the form

let v = expr1 in expr2

declares a variable v that's local to expr2. Its value (which can never be changed) is given by expr1.

You can use this kind of expression anywhere, hence you can use it in an if expression.

A reasonably faithful translation of your C code would be something like this:

if 1 = 1 then
    3
else
    let j = 5 in
    j

Upvotes: 5

V. Michel
V. Michel

Reputation: 1619

This is valid but not very useful.

let i=1;;
if i = 1 then 
  3 
else ( 
  let j=5 in
  j
) ;;          

- : int = 3

Upvotes: 1

Related Questions