How to create an option type F # mutable?

I need to create an option<T> mutable type in F #. I tried to write

 let x = ref None 

and subsequently recording

 x := Some(z) 

but that will not work. Help!

+4
source share
2 answers

You need to specify the type explicitly in order to avoid the "Cost Limit" (or see "Automatic generalization" in msdn ):

 let x : Ref<int option> = ref None x := Some 4 
+7
source

Also note that you only encounter this problem when entering code in F # interacative in turn. If you enter the first line without providing type annotations, you will receive an error message:

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

However, if you enter more code that uses the cell ref x (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 win. There is no need for any annotations. For instance:

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

This will work fine because F # will infer the type x from the second line. This means that you probably don't need type annotations if you send code in F # interactively for testing in large portions (and in compiled F # code you will almost never encounter this problem).

+4
source

Source: https://habr.com/ru/post/1303216/


All Articles