56 people like it.

Unfolding Sequences

Demonstrates how to use unfold to create an infinite list of the fibonacci numbers

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
// create an infinite list of fibonacci numbers
let fibs =
    Seq.unfold
        (fun (n0, n1) ->
            Some(n0, (n1, n0 + n1)))
        (1I,1I)

// take the first twenty items from the list
let first20 = Seq.take 20 fibs

// print the finite list
printfn "%A" first20
val fibs : seq<System.Numerics.BigInteger>

Full name: Script.fibs
module Seq

from Microsoft.FSharp.Collections
val unfold : generator:('State -> ('T * 'State) option) -> state:'State -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.unfold
val n0 : System.Numerics.BigInteger
val n1 : System.Numerics.BigInteger
union case Option.Some: Value: 'T -> Option<'T>
val first20 : seq<System.Numerics.BigInteger>

Full name: Script.first20
val take : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.take
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

More information

Link:http://fssnip.net/w
Posted:7 years ago
Author:Robert Pickering
Tags: lazy , seq , unfold