ocaml

I don't understand why the result of the last statement is 6


let x = 2;;

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

let x = 3 and y = x + 1 
in x + y;;

The results are ordered respectively to each expression:

val x : int = 2

- : int = 7

- : int = 6

Can you help me understand why the last expression equals 6, it's hard for me to understand it.

I run this code in tryOCamlpro.


Solution

  • The first one is self-explanatory.

    The second one should warn you that y is unused. x is 3, so x + 1 is 4. Your observed result of 7 suggests that the code you've shown us is not actually what you evaluated.

    For the third, let's try something a bit different:

    # let x = 3 and y = x + 1 
    in (x, y);;
    - : int * int = (3, 3)
    

    Huh. Let's fire up a clean interpreter environment and try that:

    # let x = 3 and y = x + 1 in (x, y);;
    Error: Unbound value x
    

    From this we can see that the definition of y wasn't using the x defined as 3 but rather the previous definition of x as 2.

    You likely wanted:

    # let x = 3 in 
      let y = x + 1 in 
      x + y;;
    - : int = 7
    

    When you use let <pattern> = <expr> and <pattern> = <expr> or let <pattern> = <expr> and <pattern> = <expr> in <expr> the definitions are independent of one another. As a result, this is much less common than let <pattern> = <expr> let <pattern> = <expr> or let <pattern> = <expr> let <pattern> = <expr> in <expr>

    If we modify this construct to let rec <pattern> = <expr> and <pattern> = <expr> or let rec <pattern> = <expr> and <pattern> = <expr> in <expr> we can define mutually recursive functions. This is not common.