bbaja42
bbaja42

Reputation: 2169

How does Ocaml variable scope work?

I'm starting learning Ocaml, using hickey book, and I'm stuck on Exercise 3.4, part 9

let x x = x + 1 in x 2

The result of the operation is 3, but I don't understand why?

Upvotes: 5

Views: 666

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 47382

When you write let x x = ... you are defining a function called x which binds the name x to its argument.

Since you used let instead of let rec, the function doesn't know its own name, so as far as it knows, the only x worth knowing about is the one passed in as an argument.

Therefore when you call the function with x 2, it binds the value 2 to the name x and evaluates x+1, getting 3 as the result.

Upvotes: 7

Related Questions