I am a F# newbie and I have a (probably simple) question.
The purpose of the code below is to copy the values from the sequence (bytestream) into the array myarray_, keeping the size of the array thesize, and having other elements set to zero.
I can see the values being copied in the for loop. But after leaving the constructor, the debugger shows that myarray_ of the newly constructed object contains all zeros!
I am using VS2012. Thanks.
EDIT: The size of the recipient array is always bigger than the size of the incoming sequence.
EDIT: The object of this SomeClass is actually instantiated as a member of an outer class. Here it is, along with more context in ‘SomeClass’.
When the main program calls OuterClass.Func, the “cp” objects gets created, and the array gets properly populated. When the code leaves the ctor the array either contains all zeros, or it has size zero (see comments below).
** SOLVED? ** : I changed “cp” from “member” to “let mutable”… it seems to work now. Not sure to understand why.
type SomeClass(thesize, bytestream : seq<byte>) = class
let mutable myarray_ = Array.create<byte> thesize 0uy
do
let mutable idx = 0
for v in bytestream do
myarray_.[idx] <- v
idx <- idx + 1
member x.Func(index) = // consumes myarray_.[index] and neighbor values
type OuterClass(thesize, bytestream) = class
member x.cp : SomeClass = new SomeClass(thesize, bytestream)
member x.Func(index) =
x.cp.Func(index)
You declare
myarray_as a mutable value, so it’s possible to assign it to a newly created array somewhere in your code. You should not usemutablekeyword because you want to update array elements, not change the array to a new one.Assume that
thesizeis bigger than length ofbytestream:EDIT:
With
you essentially instantiate a new instance of
SomeClasseach time the property is used. Therefore, you will not see the effects ofx.Funcon the oldSomeClass. What you probably want is:where the instance is only constructed once in the default constructor.