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
let
one= seq { 0 .. 100 }
printfn "%A" one
 

//Sequence using Range Expressions of characters

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

//Sequence with increment

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

//sequence with yield keyword

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

//sequence with -> operator

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

//Sequence with decrement

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

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

Output

sequences in f#

Seq Module Functions

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

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

Output:

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
for
n in one do
printfn "%d " n

Output:

seq.unfold in f#

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

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

Output:

seq.tolist in f#

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

Seq.iter:
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

Output:

seq.iter in f#

Seq.map:
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|]
let
two = one |> Seq.map (fun x -> x * x)
printfn "%A" one
printfn "%A" two

Output:

seq.map in f#


Similar Articles