Skip to content
This repository was archived by the owner on Nov 26, 2024. It is now read-only.

Latest commit

 

History

History
86 lines (54 loc) · 2.82 KB

File metadata and controls

86 lines (54 loc) · 2.82 KB
title Seq.unfold<'State,'T> Function (F#)
description Seq.unfold<'State,'T> Function (F#)
keywords visual f#, f#, functional programming
author dend
manager danielfe
ms.date 05/16/2016
ms.topic language-reference
ms.prod visual-studio-dev14
ms.technology devlang-fsharp
ms.assetid 3f3ee704-139b-408e-a406-a938b2061f70

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)

Syntax

// 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.

[!code-fsharpMain]

Output

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

Collections.Seq Module (F#)

Microsoft.FSharp.Collections Namespace (F#)