Mutables end up having their memory allocated on the stack. Because of that, mutables cannot be captured by closures (if you held a reference to something on the stack, it would get trashed as soon as the function returns). refs on the other hand are on the heap so they can be captured by closures. You can see this in action by trying the following two samples:

1
2
3
4
//Try to return a function which modifies a mutable
let f = 
    let mutable x = 5
    (fun y -> x <- x * y)
1
2
3
4
5
6
//Try to return a function which modifies a ref
let g = 
    let x = ref 5
    (fun y -> x := !x * y)

g compiles, but f complains about how mutables can't be captured by closures. There's probably also some speed benefits to using mutables since they're on the stack. That's the main differences I can think of.

By on 4/9/2009 8:47 AM ()
By on 4/9/2009 9:22 AM ()
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