How to concatenate lists (and other collections) in F#?
Solution 1
sequence and list together
There is no special function for this. If the sequence is first and the list is the second, then you have to choose between converting the first one to list (and then copying it when appending using List.append
) or using Seq.append
followed by List.ofSeq
which will copy both lists.
So it would make sense to write your own function.
list and list together into a list? (non-destructive)
List.append
does this.
list and list together into a list if it is destructive
Lists are immutable, so there is no destructive append.
mutable arrays together, destructively, into another mutable array?
In .NET, you cannot resize arrays, so there is no destructive way of doing that. Array.append
creates a new array (and would be faster than other options, because it knows the size of the result in advance).
And can you concatenate tuples too?
No. The type system does not let you express the type of a function that would append tuples (they have to have a statically known size).
Solution 2
The @ operator is a simple & tidy way to join multiple lists:
let allElements = list1 @ list2 @ list3 @ list4 @ list5 @ list6
Related videos on Youtube
Tim Lovell-Smith
Updated on June 04, 2020Comments
-
Tim Lovell-Smith almost 4 years
Does F# provide idiomatic ways to concatenate
- sequence and list together?
- list and list together into a list? (non-destructive)
- list and list together into a list if it is destructive?
- mutable arrays together, destructively, into another mutable array?
And can you concatenate tuples too?
-
MarcinJuraszek about 9 yearsThat's a lot of questions. And not of them is actually specific enough to provide meaningful answer... Is there particular problem you're trying to solve?
-
Tim Lovell-Smith about 9 yearsHm. I just want to reap the benefits of expert knowledge - I think that someone who is experienced with the language should be able to explain these concepts. But I agree it doesn't really fit proper Q&A format. Let me scope it down.
-
YotaXP about 9 yearsThere is also the
@
operator, which I believe is identical toList.append
. -
Scott Hutchinson almost 5 yearsIt should be mentioned that the @ operator (and List.append) can be very slow. So if performance is a concern, they should be avoided by instead recursively calling the cons operator :: to copy the head from one list to another.