Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a sequence in F# as opposed to a list?

Tags:

list

f#

I understand that a list actually contains values, and a sequence is an alias for IEnumerable<T>. In practical F# development, when should I be using a sequence as opposed to a list?

Here's some reasons I can see when a sequence would be better:

  • When interacting with other .NET languages or libraries that require IEnumerable<T>.
  • Need to represent an infinite sequence (probably not really useful in practice).
  • Need lazy evaluation.

Are there any others?

like image 848
dodgy_coder Avatar asked May 30 '12 10:05

dodgy_coder


People also ask

What is a sequence in F#?

A sequence is a logical series of elements all of one type. Sequences are particularly useful when you have a large, ordered collection of data but do not necessarily expect to use all of the elements.

Is a sequence a set?

A Sequence is like a Set, except: the terms are in order (with Sets the order does not matter) the same value can appear many times (only once in Sets)

What is yield in F#?

yield! (pronounced yield bang) inserts all the items of another sequence into this sequence being built. Or, in other words, it appends a sequence.


1 Answers

I think your summary for when to choose Seq is pretty good. Here are some additional points:

  • Use Seq by default when writing functions, because then they work with any .NET collection
  • Use Seq if you need advanced functions like Seq.windowed or Seq.pairwise

I think choosing Seq by default is the best option, so when would I choose different type?

  • Use List when you need recursive processing using the head::tail patterns
    (to implement some functionality that's not available in standard library)

  • Use List when you need a simple immutable data structure that you can build step-by-step
    (for example, if you need to process the list on one thread - to show some statistics - and concurrently continue building the list on another thread as you receive more values i.e. from a network service)

  • Use List when you work with short lists - list is the best data structure to use if the value often represents an empty list, because it is very efficient in that scenario

  • Use Array when you need large collections of value types
    (arrays store data in a flat memory block, so they are more memory efficient in this case)

  • Use Array when you need random access or more performance (and cache locality)

like image 97
Tomas Petricek Avatar answered Sep 21 '22 18:09

Tomas Petricek