Partager via


Seq.unfold<'State,'T> Function (F#)

Returns a sequence that contains the elements generated by the given computation.

Namespace/Module Path: Microsoft.FSharp.Collections.Seq

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
Seq.unfold : ('State -> ('T * 'State) option) -> 'State -> seq<'T>

// Usage:
Seq.unfold generator state

Parameters

  • generator
    Type: 'State -> 'T * 'State option

    A function that takes the current state and returns an option tuple of the next element of the sequence and the next state value.

  • state
    Type: 'State

    The initial state value.

Return Value

The result sequence.

Remarks

The given initial state argument is passed to the element generator. For each IEnumerator elements in the stream are generated on-demand by applying the element generator, until a None value is returned by the element generator. Each call to the element generator returns a new residual state.

The stream will be recomputed each time an IEnumerator is requested and iterated for the sequence. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently.

This function is named Unfold in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.

Example

The following code demonstrates the use Seq.unfold to generate two sequences. The first just generates a sequence of integers. The second generates a sequence of Fibonacci numbers, which are composed by adding the two previous numbers in the sequence. The first two numbers in the Fibonacci sequence are (1, 1), which forms the initial state parameter. The state at each step consists of the two numbers whose sum produces the next Fibonacci number.

let seq1 = Seq.unfold (fun state -> if (state > 20) then None else Some(state, state + 1)) 0
printfn "The sequence seq1 contains numbers from 0 to 20." 
for x in seq1 do printf "%d " x
let fib = Seq.unfold (fun state ->
    if (snd state > 1000) then None
    else Some(fst state + snd state, (snd state, fst state + snd state))) (1,1)
printfn "\nThe sequence fib contains Fibonacci numbers." 
for x in fib do printf "%d " x
The sequence seq1 contains numbers from 0 to 20.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
The sequence fib contains Fibonacci numbers.
2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Platforms

Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Reference

Collections.Seq Module (F#)

Microsoft.FSharp.Collections Namespace (F#)