Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ocaml variable scope work?

Tags:

ocaml

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?

like image 442
bbaja42 Avatar asked May 14 '12 12:05

bbaja42


Video Answer


1 Answers

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.

like image 55
Chris Taylor Avatar answered Sep 24 '22 20:09

Chris Taylor