Some good answers already; I would also point you at

[link:lorgonblog.spaces.live.com]

for some commentary. In general I would say "use mutable when you can, use ref when you have to because you want to do aliasing/by-reference or because you want to capture mutables in a lambda". (And of course, that advice only applies if you've decided to opt into mutability in the first place; prefer immutability when possible and reasonable/performant.)

By on 11/19/2008 7:48 PM ()

Another thing just occured to me, although I haven't had a chance to try it. Is a ref cell the correct way to pass an argument to a C# method that takes a ref or out parameter? If not, what is the correct way?

By on 11/20/2008 5:45 AM ()

Hi, you can use both:

1
2
3
4
5
6
7
// Using ref-cell
let n = ref 0
Int32.TryParse("10", n)

// Using mutable locals:
let mutable n = 0
Int32.TryParse("10", &n)

However, this is a bad example. In most of the cases you can use another great F# feature - it allows you to treat "out" arguments simply as resutls of the method call:

1
2
3
 
let success, result = Int32.TryParse("10");;
if success then // do something with 'result'
By on 11/20/2008 5:53 AM ()

Hi,
yes, ref-cells are defined exactly as <i>divisortheory<i> written. There are some differences between these two - most importantly the following: You can create "aliases" for reference cells, which can lead to a more dangerous code: <code lang=fsharp> let a = ref 10 let b = a b := 20 printfn "%d" !a // gives 20! </code> On the other side, there are situations where you can't use mutable locals, because of a (I believe intentional) limitation in the compiler: <code lang=fsharp> > let counter() = let mutable a = 0 (fun () -> a <- a + 1; a );; error FS0191: The mutable variable 'a' 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 '!'. </code> So in this case, you'd have to write this using "ref". In general, I tend to use "mutable" whenever possible (because it is easier to see what is going on) and use "ref" only when I have a situation like this, where "mutable" doesn't work. T. <H2 class=CommonTitle> </H2>

By on 11/19/2008 7:29 PM ()

I believe ref cells are actually defined as

1
2
3
4
type 'a ref = { mutable value: 'a }
let ref x = { value = x }
let (:=) x y = x.value <- y
let (!) x = x.value
By on 11/19/2008 4:18 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