开发者

How do I create an F# mutable option type?

开发者 https://www.devze.com 2022-12-21 20:48 出处:网络
I need to create a mutable option<T> type in F#. I\'ve tried writing let x = ref None and subsequently writing开发者_StackOverflow社区

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

let x = ref None

and subsequently writing

开发者_StackOverflow社区
x := Some(z)

but it doesn't work. Help!


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


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消