Reputation: 1162
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.
Upvotes: 7
Views: 10284
Reputation: 25008
You can use Array.append
with mutable
arrays:
let mutable my_array = [||]
for i in 0 .. array_size do
my_array <- [|i|] |> Array.append my_array
// my_array <- Array.append my_array [|i|]
printfn "my array is: %A" my_array
Upvotes: 0
Reputation: 43076
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
Upvotes: 7
Reputation: 4280
For any Seq
which is IEnumerable<T>
alias in F# you can write this function:
let addToSequence aseq elm = Seq.append aseq <| Seq.singleton elm
And use it this way:
let withSomeone = addToSequence [||] "Someone"
You can use Seq.toArray
or Seq.toList
after you get a result sequence
Upvotes: 4
Reputation: 11415
Take a look at Array.append.
// Signature: Array.append : 'T [] -> 'T [] -> 'T []
// Usage: Array.append array1 array2
So in your case, you can use it like this:
let name = "someone"
let mutable arrayOfNames = Array.append [|"test"; "abc"|] [|name|]
printfn "%A" arrayOfNames
//[|"test"; "abc"; "someone"|]
So you simply need to transform your string into an array (by using [|string|]). Since Array
contains the append
function, you can append a string this way to an array.
Upvotes: 2