I am learning Jason Hickey’s Introduction to Objective Caml. Just have a question about the expression thing.
So it says:
Definitions using let can also be nested using the in form.
let identifier = expression1 in expression2
The expression expression2 is called the body of the let. The variable named identifier
is defined as the value of expression1 within the body. The identifier is defined only in
the body expression2 and not expression1.
A let with a body is an expression; the value of a let expression is the value of
the body.
let x = 1 in
let y = 2 in
x + y;;
let z =
let x = 1 in
let y = 2 in
x + y;;
val z : int = 3
Ok. I don’t understand much about the above statements.
First
The variable named identifier
is defined as the value of expression1 within the body. The identifier is defined only in
the body expression2 and not expression1.
What does this mean? So identifier is the value of expression1, but only in the body expression2? Does it mean that identifier is effective only in expression2but has the value of expression1? Then does defining identifier make sense, as it is only in expression2?
Second
Let’s see the example:
let x = 1 in
let y = 2 in
x + y;;
So I don’t see the point of this let statement. x = 1 for sure, what’s the point of giving a body of let y=2 in x+y;;?
Third
let z =
let x = 1 in
let y = 2 in
x + y;;
So how can I sort out the logic of this statement?
if take this definition form: let identifier = expression1 in expression2
What’s the expression1 in the let statement above? Is it let x = 1?
Can anyone tell me the logic of nesting let in a kind of Java way? or more understandable way?
Yes. When I do
let x = 42 in x+x, thenxhas the value42in the expressionx+x, butxdoesn’t have any value outside of theletexpression. So if you typed something like this in the interpreter:The result of
x+xwould be84, but the result ofx*2would be an error becausexis not defined in that scope.Sure, why not? I mean in this specific example where
xis defined to be a single number, it might not make all that much sense, but in a real world scenario, it would probably be a larger expression and not having to repeat it multiple times becomes a big advantage.Also
expression1might have side-effects that you only want to execute once (e.g. if you want to assign user-input to a variable).You mean: why not just write
1+2? Again, in a real world scenario you’ll have more complicated expressions and you don’t want to have them all on one line. Also giving names to values generally increases readability (though not really in this example).Here
let z = ...is aletstatement, i.e. it defines the namezglobally and doesn’t have a body. So the entire expression to the right of the first=is the value ofz. For thelet x = ... in ...bit,1is theexpression1andlet y = 2 in x+yis theexpression2. And fory2is theexpression1andx+yis theexpression2.