F#,赋值运算符与集合运算符 [英] F#, assignment operator vs set operator
问题描述
我已经开始使用F#,某些代码结构使我感到惊讶.例如:
I have started with F# and some code structure wonder me. For example:
我有下一个代码:
let mutable s = 10
s <- 1 + s
printf "%i" s
从数学角度看,一切都是清楚的.我将"s"标记为可变的,并将新值分配给"s".结果是11.
Everything is clear from math side. I marked "s" as mutable and assigned the new value to "s". Result is 11.
让我尝试其他代码部分:
Let me try other part of code:
let mutable s = 10
s = 1 + s
printf "%i" s
此代码有效.但是我发现s = 1 + s
从数学角度来说有点奇怪.执行此操作的结果为10.
This code was worked. But I see that s = 1 + s
is a bit strange from the math side. Result of executing of this was 10.
我的问题是,上一个样本中发生了什么?为什么我没有收到错误消息?只是s = 1 + s
被忽略了吗?为什么?我的输出没有任何错误.
My question, what go on in the last sample? Why didn't I get a error? Is s = 1 + s
just ignored? Why? I didn't get any error in the output.
推荐答案
回答第二个问题-
为什么我没有收到错误消息? s = 1 + s是否被忽略?为什么?我的输出没有任何错误.
Why didn't I get a error? Is s = 1 + s just ignored? Why? I didn't get any error in the output.
这样做的原因是F#区分了脚本文件中的顶级作用域和本地作用域.当您在脚本文件(Visual Studio或Try F#中的*.fsx
文件)中时,可能要编写一个表达式序列(可能返回一个值)并逐个交互地执行它们.这意味着当您在一行上写s = 1 + s
时,这不是错误,因为您可以评估该行(选择它并按Ctrl + Enter或Alt + Enter),然后在交互式输出中查看结果.
The reason for this is that F# distinguishes between top-level scope in a script file and local scope. When you are in a script file (*.fsx
file in Visual Studio or inside Try F#), then you probably want to write a sequence of expressions (that may return a value) and execute them interactively one by one. This means that when you write s = 1 + s
on one line, this is not an error because you can evaluate the line (select it and hit Ctrl+Enter or Alt+Enter) and see the result in the interactive output.
但是,当它出现在函数内部(或在其他本地范围中,您不希望对其进行交互式评估)时,会收到警告.最简单的查看方法是使用do
创建本地范围(这在Try F#中也适用):
However, when this appears inside a function (or in other local scope where you are not expected to evaluate it interactively), you get a warning. The easiest way to see is to create a local scope using do
(and this works in Try F# too):
do
let mutable s = 10
s = 1 + s // Warning: This expression should have type 'unit',
// but has type 'bool'. If assigning to a property
// use the syntax 'obj.Prop <- expr'.
printf "%i" s
这篇关于F#,赋值运算符与集合运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!