Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 948
Tim Lovell-Smith Avatar asked Feb 17 '15 17:02

Tim Lovell-Smith


People also ask

How do you concatenate multiple lists in Python?

You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object. What is this? Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.

Can we concatenate two lists how?

The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation. List comprehension can also accomplish this task of list concatenation.

What do you mean by concatenation in list explain with example?

What Is Concatenation? Concatenation of lists is an operation where the elements of one list are added at the end of another list. For example, if we have a list with elements [1, 2, 3] and another list with elements [4, 5, 6] .


1 Answers

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).

like image 68
Tomas Petricek Avatar answered Sep 28 '22 06:09

Tomas Petricek