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, next = state
        if cur < 0 then  // overflow
            None
        else
            let next' = cur + next
            let state' = next, next'
            Some (cur, state') 
    (0, 1)
    |> Seq.unfold generator

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

// 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 next : int
union case Option.None: Option<'T>
val next' : int
val state' : int * int
union case Option.Some: Value: 'T -> Option<'T>
module Seq

from Microsoft.FSharp.Collections
val unfold : generator:('State -> ('T * 'State) option) -> state:'State -> seq<'T>
val first20 : int []
val take : count:int -> source:seq<'T> -> seq<'T>
val toArray : source:seq<'T> -> 'T []
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

More information

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