简体   繁体   中英

F# / .NET: add an element to an array of List<T>

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?

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())

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