How to concatenate lists (and other collections) in F#?

11,990

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
Share:
11,990

Related videos on Youtube

Tim Lovell-Smith
Author by

Tim Lovell-Smith

Updated on June 04, 2020

Comments

  • Tim Lovell-Smith
    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
      MarcinJuraszek about 9 years
      That'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
      Tim Lovell-Smith about 9 years
      Hm. 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
    YotaXP about 9 years
    There is also the @ operator, which I believe is identical to List.append.
  • Scott Hutchinson
    Scott Hutchinson almost 5 years
    It 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.