5 people like it.

Unfolding Sequences

Demonstrates how to use unfold to create a sequence of fibonacci numbers

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
// Create an infinite list of fibonacci numbers.
let fibs =
    let generator state =
        let (cur, prev) = state
        let next = cur + prev
        let state' = (next, cur)
        Some (cur, state')
    let more =
        (1, 0)
        |> Seq.unfold generator
    seq {
        0
        yield! more
    }

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

// Print the finite list.
printfn "%A" first20
val fibs : seq<int>
val generator : (int * int -> (int * (int * int)) option)
val state : int * int
val cur : int
val prev : int
val next : int
val state' : int * int
union case Option.Some: Value: 'T -> Option<'T>
val more : seq<int>
module Seq

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

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>
val first20 : seq<int>
val take : count:int -> source:seq<'T> -> seq<'T>
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

More information

Link:http://fssnip.net/w
Posted:1 year ago
Author:Dave Yost
Tags: lazy , seq , unfold , fibonacci