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”
1st version
#light
let samplefn() =
let z = 2
let z = z * 2
printfn "hi"
samplefn()
2nd version
#light
let samplefn() =
let z = 2
let z = z * 2
samplefn()
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.
Edit: 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"
A
letthat 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 isprintfn "hi", while the second example has no body. That’s what the compiler is complaining about.Note that in your function definitions the inner
letexpressions actually create nested scopes. That is, thelet z = z * 2actually creates a new value calledzand binds to it the value of the outerztimes 2, then uses it in the body of thelet(which is theprintfnin this case). A nestedletwill always have a body. It is the nesting which allows the seemingly duplicate definition.Since an outermost
letdoes not need a body, the compiler thinks you’re trying to redefinezin the same scope, which is an error. You can use parentheses to tell the compiler how to properly interpret the last example:The above will print