未考虑If-Else表达式后缩进更改吗? [英] Indentation change after if-else expression not taken into account?
本文介绍了未考虑If-Else表达式后缩进更改吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于此,此运算符用于评估管道中的副作用
let inline (|>!) a f = f a ; a
和此代码片段
if 1 = 1 then
"same"
else
"different"
|>! printfn "The numbers are %s."
|> printfn "Yes, they are %s."
这永远不会打印The numbers are same
,但它会打印Yes, they are same
。
为什么这里忽略了副作用运算符|>!
,而考虑了|>
,尽管缩进相同?
我必须以不同的方式定义副作用运算符吗?
按照这样编写,它可以按预期工作。
if 1 = 1 then "same"
else "different"
|>! printfn "The numbers are %s."
|> printfn "Yes, they are %s."
代码的实际行为就像是编写的一样,这对我来说只是不直观的吗
if 1 = 1 then
"same"
else
"different"
|>! printfn "The numbers are %s." // with indent here
|> printfn "Yes, they are %s."
推荐答案
这不是错误,并且不会专门针对长度超过两个字符的运算符发生。这是F#允许的偏移量规则的有趣结果。
当对齐同一嵌套级别的行时,它们必须处于相同的缩进,如下所示:
let foo =
bar
baz
qux
但不允许:
let foo =
bar
baz // Indented too much to the left
qux
这也不是:
let foo =
bar
baz // Indented too little
qux
在处理创建嵌套块的构造(如if
/then
)时,此规则用于确定块何时结束:何时破坏缩进对齐。
let x =
if 1 = 1 then
bar
baz
qux
但此规则有一个例外:如果行以运算符开头,则允许它最多左移运算符大小加1个字符,并且它仍将被视为当前缩进(&Q;C)。
例如,这是可行的:
let x =
1
+ 2
+ 3
但当您有不同大小的运算符时,就会变得很棘手。这是可行的:
let x =
1
+ 2
+ 3
<> 6
但这不是:
let x =
1
+ 2
+ 3
<> 6
👆这不起作用,因为2
和3
左移了比运算符大小加一个字符更多的。
您的情况是这样的:
- 第一个
printfn
被视为else
块的一部分,因为它恰好与"different"
完全对齐,但按运算符大小加1向左移动。 - 但是,第二个
printfn
比运算符大小加1左移了,因此它不再是else
的一部分。 - 但它仍然是正确的语法,因为现在它可以是周围块的一部分,并将
if
/then
/else
的整个结果通过管道传递到其中。 - 通常会出现语法错误,就像我在上面的
1+2+3 <> 6
示例中一样,但在这种情况下,语法恰好对齐(或者,可能是只是错误的)。
您可以通过删除第二个printfn
前面的空格来验证这一点:
if 1 = 1 then
"same"
else
"different"
|>! printfn "The numbers are %s."
|> printfn "Yes, they are %s."
现在,第二个printfn
将成为else
的一部分,您将得到一个错误:types string and unit don't match
。这是因为then
返回string
,但else
现在返回unit
。可以通过修改then
部分:来修复此问题
if 1 = 1 then
()
else
"different"
|>! printfn "The numbers are %s."
|> printfn "Yes, they are %s."
现在这段代码会编译,不会打印任何内容。如果您将1 = 1
替换为1 = 2
,它将正确打印&Quot;Different&q;两次。
printfn
调用来传递整个if
/then
/else
块,则必须以某种方式断开"different"
与第一个printfn
的对齐。您自己提供的一种方法是:将"different"
与else
放在同一行。另一种方法是将"different"
缩进一点,这样它就不再与第一个printfn
:对齐
if 1 = 1 then
"same"
else
"different"
|>! printfn "The numbers are %s."
|> printfn "Yes, they are %s."
这篇关于未考虑If-Else表达式后缩进更改吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文