3 people like it.

Enumerating function

This function takes an input sequence and returns a function that returns the elements in the sequence one by one when called consecutively. The returned function will throw if called more times than there are elements in the sequence. Useful when unit testing.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
/// Creates a function from a sequence that, when called, returns the items in the sequence
let enumerate (xs: seq<_>)  = 
    use en = xs.GetEnumerator()
    fun () ->
        en.MoveNext() |> ignore
        en.Current

let f = [1;2;3;4;5] |> enumerate

f() |> printf "val = %i"
f() |> printf "val = %i"
f() |> printf "val = %i"
f() |> printf "val = %i"
f() |> printf "val = %i"
f() |> printf "val = %i" // This line will throw
val enumerate : xs:seq<'a> -> (unit -> 'a)

Full name: Script.enumerate


 Creates a function from a sequence that, when called, returns the items in the sequence
val xs : seq<'a>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val en : System.Collections.Generic.IEnumerator<'a>
System.Collections.Generic.IEnumerable.GetEnumerator() : System.Collections.Generic.IEnumerator<'a>
System.Collections.IEnumerator.MoveNext() : bool
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
property System.Collections.Generic.IEnumerator.Current: 'a
val f : (unit -> int)

Full name: Script.f
val printf : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printf
Raw view Test code New version

More information

Link:http://fssnip.net/7Rr
Posted:7 years ago
Author:Peder Sørensen
Tags: enumerator , seq , sequences , unittests