生成序列
有多種方法可以建立序列。
你可以使用 Seq 模組中的功能:
// 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
你還可以使用序列表示式:
// 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 }
}