详细语法
F# 中的许多构造有两种形式的语法可用:详细语法和轻量语法。 详细语法不常用,但优点是对缩进不太敏感。 轻量语法更短一些,使用缩进来提示构造的开始和结束,而不是用 begin
、end
、in
等这样的附加关键字。 默认语法是轻量语法。 此主题介绍未启用轻量语法时 F# 构造的语法。 始终启用了详细语法,因此,即使启用轻量语法,仍可以将详细语法用于某些构造。
构造表
下表显示了 F# 语言结构的轻量语法和详细语法,其中的上下文中,两种形式之间存在差异。 在此表中,尖括号 (<>) 包含用户提供的语法元素。 有关这些构造中使用的语法的更多详细信息,请参阅每个语言构造的文档。
语言构造 |
轻量语法 |
详细语法 |
复合表达式 |
<expression1>
<expression2>
|
<expression1>; <expression2>
|
嵌套的 let 绑定
|
let f x =
let a = 1
let b = 2
x + a + b
|
let f x =
let a = 1 in
let b = 2 in
x + a + b
|
代码块 |
(
<expression1>
<expression2>
)
|
begin
<expression1>;
<expression2>;
end
|
`for...do` |
for counter = start to finish do
...
|
for counter = start to finish do
...
done
|
`while...do` |
while <condition> do
...
|
while <condition> do
...
done
|
`for...in` |
for var in start .. finish do
...
|
for var in start .. finish do
...
done
|
`do` |
do
...
|
do
...
in
|
record |
type <record-name> =
{
<field-declarations>
}
<value-or-member-definitions>
|
type <record-name> =
{
<field-declarations>
}
with
<value-or-member-definitions>
end
|
class |
type <class-name>(<params>) =
...
|
type <class-name>(<params>) =
class
...
end
|
structure |
[<StructAttribute>]
type <structure-name> =
...
|
type <structure-name> =
struct
...
end
|
可区分联合 |
type <union-name> =
| ...
| ...
...
<value-or-member definitions>
|
type <union-name> =
| ...
| ...
...
with
<value-or-member-definitions>
end
|
接口 |
type <interface-name> =
...
|
type <interface-name> =
interface
...
end
|
对象表达式 |
{ new <type-name>
with
<value-or-member-definitions>
<interface-implementations>
}
|
{ new <type-name>
with
<value-or-member-definitions>
end
<interface-implementations>
}
|
接口实现 |
interface <interface-name>
with
<value-or-member-definitions>
|
interface <interface-name>
with
<value-or-member-definitions>
end
|
类型扩展 |
type <type-name>
with
<value-or-member-definitions>
|
type <type-name>
with
<value-or-member-definitions>
end
|
name |
module <module-name> =
...
|
module <module-name> =
begin
...
end
|
另请参阅