Siavash
Siavash

Reputation: 7853

How can you make a growing collection in F#

Is there a collection type in f# that has an "append" method, such that I can add an element to that collection as such:

(pseudo code)

let list = [1,2,3,4]
list.append( 5 )
print list

result : 1,2,3,4,5

Basically i need a collection that can grow at run time, I cant assume what size it will be. I couldn't find a way to do this with list or array in f#

UPDATE: I dont want to create a new list/array every time this will be happening many times. I want to append the already existing collection. I need to use the same name/symbol for the collection. F# doesn't allow me to redeclare or over write a collection, so this wouldnt work:

let A = [1,2,3]
let A = A.append 4  or A <- Array.appen A 4

Upvotes: 3

Views: 1131

Answers (2)

Grzegorz Sławecki
Grzegorz Sławecki

Reputation: 1797

In my opinion what You want achieve has little to do with functional approach. I wouldn't hesitate to use standard .NET List for that.

Regarding Your update: Since the lists are immutable, it's not that a new list is created every time You're prepending an element to a list. This is much smarter than copying whole existing list.

Upvotes: 0

Lee
Lee

Reputation: 144136

You can use ResizeArray:

let list = ResizeArray([1;2;3;4])
list.Add( 5 )

Upvotes: 8

Related Questions