简体   繁体   中英

Is it possible to make a third-party mutable struct “more immutable” via F#?

For example, wouldn't this type:

https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx

... having public mutable fields like this:

https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.x.aspx

... single-handedly make consuming F# code's immutability efforts kind of useless?

PS: performance must be preserved, no wrapping or dynamic instantiation of throw-away values.

PPS: I did some research and suspect the answer (negative) but would appreciate some input. It seems like a typical problem when not implementing everything in F# from scratch.

You are correct, the short answer is no. However, at least in the case of the Vector2 class you show, many of the operations are implemented in an immutable fashion when you use the static versions of the methods. For example

var vecB = Vector2.Normalize(vecA);

is an immutable call. Unless the libraries you are using support some kind of immutability, you are stuck with having to implement the immutable functionality you want to have.

F# has a design goal of being a hybrid of mutable and immutable content so that it can access the rich functionality of .NET libraries when needed.

For collections of structs , this is not an issue. The collection remains immutable irrespective of the struct's members, since getting the struct from the collection returns a copy. Altering this copy does not alter the collection's contents.

Elsewhere, structs can be used to write wrappers without additional GC load. This requires to create methods for all features you want to keep and have them call the original methods. Unless the JIT doesn't inline the calls, this shouldn't cost performance. However, when wrapping reference types, this will create an empty default constructor on the wrapper type, resulting in a null reference if this constructor is called.

As a side note, I wouldn't recommend using vector classes from outside F#, since they are not unit-of-measure aware. In my experience, most vectors can be assigned physical units, which makes code safer and more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM