我正在学习Jason Hickey's Introduction to Objective Caml。只是对表达事物有疑问。
所以它说:
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
确定。我对上述陈述不太了解。
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.
这是什么意思? identifier
the value of expression1
是expression2
,但仅限于identifier
?这是否意味着expression2
仅在expression1
中有效,但其值为identifier
?那么定义expression2
是否有意义,因为它只在let x = 1 in
let y = 2 in
x + y;;
?
让我们看看例子:
let
所以我没有看到这个x = 1
声明的重点。 let y=2 in x+y;;
当然,给出let identifier = expression1 in expression2
的身体有什么意义?
让z = 让x = 1 in 让y = 2 in x + y ;;
那么我怎样才能理清这句话的逻辑呢?
如果采用此定义形式:expression1
上面let
声明中的let x = 1
是什么?是nesting let
吗?
有人能以某种Java
的方式告诉我{{1}}的逻辑吗?还是更容易理解?
答案 0 :(得分:4)
这是什么意思?所以identifier是expression1的值,但只在body2中?这是否意味着标识符仅在expression2中有效,但具有expression1?
的值
是。当我执行let x = 42 in x+x
时,x
在表达式42
中的值为x+x
,但x
在let
之外没有任何值表达式。所以如果你在解释器中键入这样的东西:
let x = 42 in x+x;;
x*2;;
x+x
的结果为84
,但x*2
的结果将是错误,因为x
未在该范围内定义。
那么定义标识符是否有意义,因为它只在expression2?
中
当然,为什么不呢?我的意思是在这个特定的例子中,x
被定义为单个数字,它可能没有那么多意义,但在现实世界的场景中,它可能是一个更大的表达式而不必重复多个时代成为一大优势。
同样expression1
可能有副作用,您只想执行一次(例如,如果您想将用户输入分配给变量)。
所以我没有看到这个let语句的重点。 x = 1肯定,在x + y中给出一个让y = 2的体的重点是什么;;?
你的意思是:为什么不写1+2
?同样,在现实世界中,您将拥有更复杂的表达式,并且您不希望将它们全部放在一行上。同时给出值的名称通常会增加可读性(尽管在这个例子中并不是这样)。
令z = let x = 1 in let y = 2 in x + y ;;
上面的let语句中的表达式1是什么?它是否让x = 1?
此处let z = ...
是let
语句,即它全局定义名称z
且没有正文。因此,第一个=
右侧的整个表达式是z
的值。对于let x = ... in ...
位,1
是expression1
而let y = 2 in x+y
是expression2
。对于y
2
,expression1
和x+y
是expression2
。
答案 1 :(得分:1)
这是什么意思?所以identifier是expression1的值,但是 只在身体表达2?这是否意味着标识符 仅在expression2中有效但是具有expression1的值吗?然后 定义标识符是否有意义,因为它仅在expression2?
中
这就是它的含义,是的,但更简单地说,这意味着你不能在自己的价值中使用标识符。将expression1的值绑定到标识符后,可以在expression2中使用标识符而不是整个expression1。
通常,使用绑定有两个原因; 1是为了防止对给定表达式进行多次评估,2为了清楚起见:将相对复杂的表达式的值赋予人类可读的名称通常很有用。
就Java而言,let绑定大致对应于局部变量。