I have a string in F#:
let name = "Someone"
I also have an array of strings:
let mutable arraysOfNames : string[] = [||]
I want to add the string name to the array arrayOfNames. How do I do that? It doesn't have to be an array, it can be a Sequence or any other collection that I can check then if it is empty or not.
It is not possible to add an item to a zero-length array. All you can do is create a new array that holds the item. The currently accepted answer, using Array.append, does not modify the input arrays; rather, it creates a new array that contains the elements of both input arrays. If you repeatedly call append to add a single element to an array, you will be using memory extremely inefficiently.
Instead, in f#, it makes much more sense to use F#'s list type, or, for some applications, ResizeArray<'T> (which is f#'s name for the standard .NET List). If you actually need the items in an array (for example, because you have to pass them to a method whose parameter is an array type), then do as Steve suggests in his comment. Once you have built up the collection, call List.toArray
or Array.ofList
if you're using an F# list, or call the ToArray()
instance method if you're using a ResizeArray.
Example 1:
let mutable listOfNames : string list = []
listOfNames <- "Alice" :: listOfNames
listOfNames <- "Bob" :: listOfNames
//...
let names = listOfNames |> List.toArray
Example 2:
let resizeArrayOfNames = ResizeArray<string>()
resizeArrayOfNames.Add "Alice"
resizeArrayOfNames.Add "Bob"
let names = resizeArrayOfNames.ToArray()
Note that in the first example, you'll get the names in reverse order; if you need them in the same order in which they were added, you'd need
let names = listOfNames |> List.rev |> List.toArray
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With