Difference between lists and sequences

I am trying to understand the difference between sequences and lists.

In F #, there is a clear distinction between the two. However, in C #, I've seen programmers refer to IEnumerable collections as a sequence. What does an IEnumerable sequence make in the fact that it returns an object to iterate over the collection?

Perhaps the real difference is purely in functional languages?

+2


a source to share


3 answers


Not really - you usually have random access to the list, as well as the ability to quickly get its score, etc. Adrexed lists don't have a random access nature ... but then they don't implement IList<T>

. There is a gray area between the objects provided by a particular platform and general concepts.



Sequences (as presented IEnumerable<T>

) are read-only, one-to-one, one item at a time, and are potentially infinite. Of course, any implementation of a sequence can also be a list (for example List<T>

), but when you think of it as a sequence, you can basically iterate over it (re) and it.

+7


a source


I think the confusion might come from the fact that collections kind of List<T>

implement an interface IEnumerable<T>

. If you have a subtype relationship at all (for example, a supertype Shape

with two subtypes Rectangle

and Circle

), you can interpret that relationship as an "is-a" hierarchy.

That means it's fine to say " Circle

is Shape

" and people say " List<T>

is IEnumerable<T>

", that is, "list is a sequence." This makes sense because a list is a special type of sequence. In general, sequences can also be lazily generated and infinite (and these types cannot be lists either). An example of a (perfectly valid) sequence that cannot be generated by a list would look like this:



// C# version                           // F# version
IEnumerable<int> Numbers() {            let rec loop n = seq {
  int i = 0;                               yield n
  while (true) yield return i++;           yield! loop(n + 1) }
}                                       let numbers = loop(0)

      

This also applies to F #, because F # list

type also implements IEnumerable<T>

, but functional programming does not put much emphasis on the object-oriented point of view (and implicit conversions that allow "interpretation are used less often in F #).

+4


a source


The contents of the sequence are computed on demand, so you can implement, for example, an infinite sequence without affecting your memory. So, in C #, you can write a sequence like

IEnumerable<int> Null() {
  yield return 0;
}

      

It will return an infinite sequence of zeros. You can write

int[] array = Null().Take(10).ToArray()

      

And it will take 10 * 4 bytes of memory, despite the infinity of the sequence. So as you can see C # has a distinction between sequence and collection

+2


a source







All Articles