37 people like it.

Unfolding Sequences

Show's using the unfold function to create a sequence that terminates once some limit is passed.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
// the lazy list definition
let lazyList =
    Seq.unfold
        (fun x ->
            if x < 13 then
                // if smaller than the limit return
                // the current and next value
                Some(x, x + 1)
            else
                // if great than the limit 
                // terminate the sequence
                None)
        10

// print the results
printfn "%A" lazyList
val lazyList : seq<int>

Full name: Script.lazyList
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 x : int
union case Option.Some: Value: 'T -> Option<'T>
union case Option.None: Option<'T>
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view New version

More information

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