F# Sequence Generate sequences

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

There are multiple ways to create a sequence.

You can use functions from the Seq module:

// Create an empty generic sequence
let emptySeq = Seq.empty 

// Create an empty int sequence
let emptyIntSeq = Seq.empty<int> 

// Create a sequence with one element    
let singletonSeq = Seq.singleton 10 

// Create a sequence of n elements with the specified init function
let initSeq = Seq.init 10 (fun c -> c * 2) 

// Combine two sequence to create a new one
let combinedSeq = emptySeq |> Seq.append singletonSeq

// Create an infinite sequence using unfold with generator based on state
let naturals = Seq.unfold (fun state -> Some(state, state + 1)) 0

You can also use sequence expression:

// Create a sequence with element from 0 to 10
let intSeq = seq { 0..10 }

// Create a sequence with an increment of 5 from 0 to 50
let intIncrementSeq = seq{ 0..5..50 }

// Create a sequence of strings, yield allow to define each element of the sequence
let stringSeq = seq {
    yield "Hello"
    yield "World"
}

// Create a sequence from multiple sequence, yield! allow to flatten sequences
let flattenSeq = seq {
    yield! seq { 0..10 }
    yield! seq { 11..20 }
}


Got any F# Question?