cslpr
cslpr

Reputation:

understanding nested let definitions in OCaml

let quad x = let add x y = x + y in
             let double x = add x x in
             double x + double x;;

I am not able to understand how it computes 4 times the input. I understand expressions like

let x = 1 in let x = x+2 in let x = x+3 in x

evaluates as

(x -> x = x+2 in let x = x+3 in x) 1

Upvotes: 0

Views: 385

Answers (3)

zurgl
zurgl

Reputation: 1930

According to the definition of add the last expression can be rewrite as

double x + double x = add (double x) (double x)

Again by definition of add :

add (double x) (double x) = add (add x x) (add x x)

Now it's time to expand :

add (add x x) (add x x) = (add x x) + (add x x)
                        = (x + x) + (x + x)
                        = x + x + x + x

edit : Oh my god, I've not noticed, the user has disappeared :/.

Upvotes: 0

stonemetal
stonemetal

Reputation: 6208

Other than visibility of the names there is no difference between your version and this:

         let add x y = x + y;; 
         let double x = add x x;; 
         let quad x = double x + double x;;

The way to think about it is "in" creates a new scope. The x shadows the x from outer scopes. Every let bound name is new and unrelated to any name bound before. Lets hand expand it:

quad 1 = double 1 + double 1 The variable to the main function goes into the body of the function. All the let .. in stuff is just an aside until they get used. Double gets used so now we call the sub function with the parameter.

double 1 = add 1 1 Expand Double according to the definition from the let.

add 1 1 = 1 + 1 Expand Add according to the definition from the let.

Upvotes: 1

Rémi
Rémi

Reputation: 8342

let add x y = x + y in ....

define a local function, that when given an x and a y add them. its definition is only available in the ... (in you example, frome the in to the ;;

It's important to see that the fact it is let add x y = create a new x binding, that is not the x as defined in quad.

This is exaclty equivalent for ocaml, but may be clearer:

let quad x = let add a b = a + b in
             let double c = add c c in
             double x + double x;;

Upvotes: 1

Related Questions