views:

87

answers:

2

I need to create a mutable option<T> type in F#. I've tried writing

let x = ref None

and subsequently writing

x := Some(z)

but it doesn't work. Help!

+5  A: 

You need to state the type explicitly to avoid "the Value Restriction" (or see "Automatic Generalization" on msdn):

let x : Ref<int option> = ref None

x := Some 4
Johan Kullbom
+4  A: 

Also note that you face this problem only when entering the code in F# interacative line-by-line. If you enter the first line without providing type annotations, you'll get the error:

> let x = ref None;;
// Tests.fsx(1,7): error FS0030: Value restriction.

However, if you enter a larger porition of code that uses the x ref cell (for example assigns a value to it) then F# will be able to infer the type from the later part of the code, so you won't need any type annotations. For example:

> let x = ref None
  x := Some(10);;

This will work fine, because F# will infer the type of x from the second line. This means that you probably shouldn't need any type annotations if you'll send the code to F# interactively for testing in larger portions (and in a compiled F# code, you'll almost never face this problem).

Tomas Petricek