Sequences in FSharp

Introduction: A sequence represents an ordered series of elements of the same type. Sequences are important when we work with large amounts of data. It is also known as a sequence expression. It is very similar to Lists - except only one element of sequence can be exist in memory at a time. Sequences are represented by seq<T>type, which is an alias name for System.Collections.Generic.IEnumerable<T>.

Advantages of Sequences:

  • We can define an infinite sequence in easily ways.
  • It support many functions of List.
  • It has several function for extracting subsequences.
  • It provide an easy way to define sequence of items.

Syntax for Defining a Sequence

Syntax for defining a sequence is given below.

seq { exp }

Like, seq { 1..10}

Now we create some sequences using different sequence expressions.

Write the following code:

// Sequence using Range Expressions
one= seq { 0 .. 100 }
printfn "%A" one

//Sequence using Range Expressions of characters

two= seq {'a'..'z'}
printfn "%A" two

//Sequence with increment

three= seq {1..2..10}
printfn "%A" three

//sequence with yield keyword

four= seq { for i in 1 .. 5 do yield i * i }
printfn "%A" four

//sequence with -> operator

five= seq { for i in 1 .. 5 -> i * i }
printfn "%A" five

//Sequence with decrement

six= seq {10..-1..1}
printfn "%A" six

Now we run this code by pressing Ctrl+F5 key. 


sequences in f#

Seq Module Functions

The Set.Take function returns the specified number of elements from a  sequence. Write the following code:

let one= seq {1 .. 10 }
takenSeq = Seq.take 2 one
printfn "%A" takenSeq


seq.take in f#

Seq.unfold: Generates a sequence using a given function. The function provide an input value and returns an option tuple of the next value of the sequence and next iteration of Seq.unfold. Write the following code:

let one = Seq.unfold (fun state -> if (state > 10) then None else Some(state, state + 1)) 0
n in one do
printfn "%d " n


seq.unfold in f#

The Seq.toList function c
reates a list from the given collection. Write the following code:

let one = seq { 1..10 }
two = Seq.toList one
printfn "%A" two


seq.tolist in f#

Aggregate Operators in Sequence:  Seq module aggregate operators. Some of these are given below.

It iterates the given function for each element of a sequence, Like the below example.

let one = seq { 1 .. 10 }
Seq.iter (printfn "%d") one


seq.iter in f#
It creates a new sequence whose element is the outcome of applying the given function over the old sequence. Write the following code:

let one = [|1; 2; 3;4;5|]
two = one |> (fun x -> x * x)
printfn "%A" one
printfn "%A" two

Output: in f#

Similar Articles