[英]F# verbose syntax and class definition problem
I'm baffled by the fsharp-error given for following code in test.fsx
:我通过下面的代码中给出的fsharp错误困惑test.fsx
:
let Kasper = "Kasper" in printfn "%A" Kasper
type student (name: string) =
class
member this.name = name
end
let aStudent = student Kasper in printfn "%A" aStudent.name
which gives the following error,这给出了以下错误,
% fsharpc test.fsx && mono test.exe
Microsoft (R) F# Compiler version 10.2.3 for F# 4.5
Copyright (c) Microsoft Corporation. All Rights Reserved.
/Users/sporring/Desktop/test.fsx(2,1): error FS0010: Unexpected keyword 'type' in implementation file
%
I have found the following solutions:我找到了以下解决方案:
printfn "%A" Kasper.name;
移动printfn "%A" Kasper.name;
to a new line到一个新行let Kasper = "Kasper" in printfn "%A" Kasper
below the type definition移动整个结构let Kasper = "Kasper" in printfn "%A" Kasper
下面的类型定义So it seems, that I don't understand the scope of the let-in
expression.所以看起来,我不明白let-in
表达式的范围。 Would someone please help me understand why the original code fails to compile?有人能帮我理解为什么原始代码无法编译吗? Thanks.谢谢。
The verbose syntax of F# is odd and there is a good reason why it's discouraged :-). F# 的冗长语法很奇怪,有充分的理由不鼓励它:-)。
The let .. in ..
construct is an expression, but the top-level in a module (which is what you need when you also want to use type
) behaves differently. let .. in ..
构造是一个表达式,但模块中的顶层(当您还想使用type
时需要它)的行为不同。 At the module level, you can use let
to define top-level values, but this is not let .. in ..
expression but rather a declaration let <pat> = <expr>
.在模块级别,您可以使用let
来定义顶级值,但这不是let .. in ..
表达式而是声明let <pat> = <expr>
。 You can also use the do
keyword at the top-level if you want to run some code when the module is initialized, which is written as do <expr>
.如果你想在模块初始化时运行一些代码,你也可以在顶层使用do
关键字,写成do <expr>
。 So, to make your example work, you can use:因此,为了使您的示例工作,您可以使用:
#light "off"
let Kasper = "Kasper" do printfn "%A" Kasper
type student (name: string) =
class
member this.name = name
end
do let aStudent = student Kasper in printfn "%A" aStudent.name
To show more options, I write the first let
as a top-level declaration, but the aStudent
value is defined as a local binding in a do
block.为了显示更多选项,我将第一个let
写为顶级声明,但aStudent
值被定义为do
块中的本地绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.