Hi,
hiding of symbols doesn't change the value of the symbol. It simply creates a new symbol with the same name which contains a different value. The previous symbol becomes inaccessible in the scope where you hide it, but it may still be available from other places (e.g. functions declared earlier).

When looking at your code, the F# compiler actually sees something like this:

1
2
3
4
5
6
7
 
let tryPrint =
    let num1 = "one" in
    ( let printThis() = printfn "%A" num1 in
      printThis()
      let num2 = "nil" in
      ( printThis() )

The added "in" symbols and parenthesis should clarify the scope where values are accessible.
Hope this helps!

By on 1/12/2010 1:37 PM ()

thank you for both of you.

I guess I should learn without using lightweight syntax at first.

By on 1/12/2010 6:37 PM ()

another thing that I believe is good to start in FP is :

'=' is a binding NOT assignment in the typical C sense.

'<-' is assignment in F# which would be more likely give you what you expect.

By on 1/12/2010 7:03 PM ()

I tried it with a mutable value...

1
2
3
4
5
6
let tryPrint =
    let mutable num = "one"
    let printThis() = printfn "%A" num
    printThis()
    num <- "nil"
    printThis()

Now, before reading on, I suggest the reader try and guess the effect of this :)

Here's what it actually does...

It doesn't compile! On printfn "%A" num it says The mutable variable 'num' is used in an invalid way. Mutable

variables may not be captured by closures. Consider eliminating this

use of mutation or using a heap-allocated mutable reference cell via

'ref' and '!'

This works...

1
2
3
4
5
6
7
8
9
10
11
12
let tryPrint() =   // <-- add () parameter
    let num = ref "one"
    let printThis() = printfn "%A" !num
    printThis()
    num := "nil"
    printThis()


> tryPrint();;
"one"
"nil"
val it : unit = ()
By on 2/10/2010 8:23 PM ()

You will enjoy reading this:

On lambdas, capture, and mutability

[link:lorgonblog.spaces.live.com]

By on 2/10/2010 8:25 PM ()

Actually, I read it last year (and enjoyed it), but, I promise, the little bit of plagiarism was entirely unconscious! [:)]

By on 2/11/2010 1:43 AM ()

Well, the first 'num' IS shadowing the second 'num', and the function 'printThis' IS re-evaluated every time you invoke it. However, F# resolves value bindings once -- at compilation-time, not evaluation time. Also, though its not entirely relevant to your example, every 'let' binding has the potential to introduce a new scope. So, the example actually has three scopes: one introduced by 'tryPrint', one introduced by 'printThis', and the global (module) scope (inside of which 'tryPrint' is defined).

By on 1/12/2010 1:24 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper