I have a simulator that keeps some state as a record with two members: one object of Class1, and a sequence of objects of Class2.
When the simulation runs, input is read and, depending on the input, some methods of those objects are called. Such method change their internal state.
I am learning F# and I understand the importance of immutable data. However, given the complexity of such state (much more than exposed here), I think that having such objects with internal mutable state is not a big deal. At least it is hidden.
The problem is, however, another one. And it’s probably simple.
In between iterations I lose changes to “one” and “many” objects!
I guess InvokeMethodOn (obviously simplified) takes a copy of those objects.
I realize I need some kind of references here but… I am a bit lost here… State should have ref members? InvokeMethodOn should pass by ref? All of them? And what about the “many” sequence?
EDIT : There could be millions of “many” objects. Each of them has 1 or 2 KB of state (which for now is just kept in a blob of bytes).
EDIT : Changing “many” to be an array (and using Array.iter as suggested) fixed the issue. Thanks to everybody!
type State = {
one : Class1
many : Class2 seq
}
type Simulator() = class
member x.run(state : State) =
// ....
while ...
let input = ReadInput
if someFuncOf(input)
then InvokeMethodOn(state.one, input)
else Seq.iter (fun x -> InvokeMethodOn(x, input)) state.many
member x.InvokeMethodOn obj input =
obj.ChangeInternalState input
If your Class1 and Class2 contain mutable state that you change, I don’t see a reason why such change would be discarded at each iteration, unless you are recreating new copies of Class1 somehow.
If I try to script a similar thing than what is presented, it runs fines.
It would be interesting to know how your code diverge from this to find where we are missing something.
Note that in F# ref are really just a hidden representation of ‘mutable content’
You might want to read this page about mutation in FSharp
There is little magic to it and it should clarify many things.
Also one thing to note regarding mutable data is that array are mutable by default : no need to re-declare them mutable.