0

I'm not sure how to properly go through this function and determine its type. I typed it into an OCaml top level and the output is "hello world" but I do not know why. Could someone please explain how they determined the final output? Thanks!

 let f y =  
    let z = (let x = 5 in y * x) + y in "hello" in (f 7) ^ " world"
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281

2 Answers2

2

Well, the entire thing is based on the OCaml construct let a = b in c. If you match up the let and in pairs, you can see the structure of the expression.

let f y =
    let z = (let x = 5 in y * x) + y
    in "hello"
in (f 7) ^ " world"

Essentially f is a function that does some useless computation then returns "hello".

Update

This code has two slightly different uses of let a = b in c. Maybe it will be clearer to explain them separately.

The following:

let y = expr1 in expr2

defines a new name y with the value given by expr. The name y can then be used in expr2.

The following:

let f x = expr1 in expr2

defines a function f. The definition expr1 will usually use the argument x to calculate an interesting value. Then the function f can be called in expr2.

Your code has two instances of the first construct (defining values z and x), and one of the second construct (defining function f).

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
1

This function is specially obfuscated, so lets move carefully over the reduction steps:

let f y =  
    let z = (let x = 5 in y * x) + y in "hello" in (f 7) ^ " world"

==>

let f y = 
    let z = y * 5 + y in "hello" in (f 7) ^ " world"

==>

let f y = 
    let z = y * 5 + y in "hello" in (f 7) ^ " world"

At this point is obvious, that z is unused in function f, let's remove it:

let f y = "hello" in (f 7) ^ " world"

We can see, that actually we have the "function" f, that always returns "hello":

let f y = "hello"

That is defined in the scope of the expression (f 7) ^ " world". f 7 is evaluated to "hello", and we have "hello world".

The

let <name> = <expr-1> in <expr-2> 

has the following rules of evaluation:

  1. evaluate <expr-1>
  2. substitute each free occurrences of <name> in <expr-2> with <expr-1>
  3. evaluate <expr-2>
ivg
  • 34,431
  • 2
  • 35
  • 63