Reputation: 443
I have the following F# code:
let list = Array.create 5 (new ResizeArray<char>())
list.[0].Add('c')
printfn "%A" list
This is the output in FSI console:
[|seq ['c']; seq ['c']; seq ['c']; seq ['c']; seq ['c']|]
Seems pretty strange to me, as I was trying to add 'c' to the first index only, but it seems to add to ALL the indices in the array. What am I doing wrong?
Upvotes: 2
Views: 1495
Reputation: 1319
Your list
is an array of 5 elements, but each element is referencing the same list. You can check this with the following code:
let d = list.[0].Equals(list.[1])
d
will be true.
This is because of the way you are initializing the list - you are creating a list with 5 elements where all 5 elements are the same value.
Therefore, when you do the list.[0].Add('c')
, it correctly appends the element to the first list in the array, but because all the elements are referencing the same list, it seems as if it is appending it to every element.
You can do this to initialize your list, with expected results (each element is referencing a different list):
let list = [| for i in 1 .. 5 -> new ResizeArray<char>() |]
As ildjarn stated, this is an even better way of doing it:
let list = Array.init 5 (fun _ -> ResizeArray())
Upvotes: 5