Scope / evaluation order of nested `let .. in..` in OCaml

I have a few problems here that I do not understand 100%:

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

I know that the result of this expression is 6, but I just want to make sure that the calculation order of this expression; which part is calculated first?

+3
source share
3 answers

You asked about the evaluation order in the expression let x=1 in let x=x+2 in .... Order from left to right! When you have a chain let a=b in let c=d in ..., the evaluation order is always from left to right.

: x let. , , let x=x+1, , "" x " x". "" "x" , OCAML! , , , ,

 let x = 1 in let y = x+2 in let z = y+3 in z;;

, . ( let.) "x" , x, y z. . .

? " x = 1 y = x + 2", " x = 1 x = y + 2"? x=x+2 ! , let x=aaa in bbb.

  let x=aaa in bbb

, aaa,

  (fun x -> bbb) aaa

, : -, OCAML "bbb" , "aaa" . ( let x=aaa in bbb , aaa, bbb, " ".) -, "x" "x" "aaa" . , "aaa" "x" , , "x" . .

:

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

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

let :

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

, :

 (fun x -> (fun y -> (fun z -> z) y+3) x+2 ) 1

,

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

, .

+8

parens:

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

(x = 1), x x let:

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

:

let x = 3 in (let x = (x+3) in x)

:

let x = (3+3) in x

:

let x = 6 in x

:

6
+4

( , .)

, . . OCaml , .. ( ) . :

let v = e1 in e2

The variable is vnot visible (i.e. cannot be named) c e1. If (by chance) a variable of this name appears in e1, it must refer to some external definition (other) v. But the new vone can (of course) be called c e2. So your expression is equivalent to the following:

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

It seems to me that this is clearer, but it has exactly the same meaning.

+4
source

All Articles