F#中的函数..为什么不编译 [英] functions in F# .. why is it not compiling
问题描述
我写了两个版本的代码.第一个按预期方式工作并显示"Hi".第二个错误给我一个错误,在此之后的块未完成"
I have written two versions of code. The first one works as expected and print "Hi". the second one gives me error that "block following this let is unfinished"
第一个版本
#light
let samplefn() =
let z = 2
let z = z * 2
printfn "hi"
samplefn()
第二版
#light
let samplefn() =
let z = 2
let z = z * 2
samplefn()
唯一的区别是第二个版本中没有printfn.我正在使用Visual Studio 2010作为我的IDE.我是F#的新手,但这个错误对我来说似乎很奇怪.我想我缺少一些非常重要的概念.请解释.
Only difference is the printfn is absent in the second version. I am using Visual Studio 2010 as my IDE. I am very new to F# but this error seems very strange to me. I guess I am missing some very important concept. Please explain.
同样,如果我在函数外部执行此操作,即使使用第一版代码,也会出现错误.
Also if I do it outside the function I get error even with the first version of code.
#light
let z = 2
let z = z * 2
printfn "Error: Duplicate definition of value z"
推荐答案
一个不在顶层(例如,缩进的)的let
必须具有称为a的语句(实际上是一个表达式,如pst所指出的)作业后的正文".在第一个示例中,主体为printfn "hi"
,而第二个示例中没有主体.这就是编译器所抱怨的.
A let
that is not at the top level (e.g. your indented ones) has to have a statement (actually an expression, as pst notes) called a "body" following the assignment. In the first example the body is printfn "hi"
, while the second example has no body. That's what the compiler is complaining about.
请注意,在函数定义中,内部let
表达式实际上会创建嵌套作用域.也就是说,let z = z * 2
实际上创建一个名为z
的新值,并将其与外部z
的值乘以2,然后在let
的主体(即printfn
这个案例).嵌套的let
将始终具有主体.这是嵌套,它允许看似重复的定义.
Note that in your function definitions the inner let
expressions actually create nested scopes. That is, the let z = z * 2
actually creates a new value called z
and binds to it the value of the outer z
times 2, then uses it in the body of the let
(which is the printfn
in this case). A nested let
will always have a body. It is the nesting which allows the seemingly duplicate definition.
由于最外面的let
不需要主体,因此编译器认为您正在尝试在同一范围内重新定义z
,这是错误的.您可以使用括号告诉编译器如何正确解释最后一个示例:
Since an outermost let
does not need a body, the compiler thinks you're trying to redefine z
in the same scope, which is an error. You can use parentheses to tell the compiler how to properly interpret the last example:
let z = 2
(let z = z * 2
printfn "z = %d" z)
printfn "z = %d" z
上面将打印
z = 4
z = 2
这篇关于F#中的函数..为什么不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!