1 people like it.

Seq.tryTake with proper lifetime

Fixes http://www.fssnip.net/1K/title/SeqtryTake by moving the enumerator into the `seq` computation and using `use` instead of `let` to dispose the enumerator at the end.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
module Seq =
    let tryTake (n : int) (s : _ seq) =
        seq {
            use e = s.GetEnumerator ()
            let mutable i = 0
            while e.MoveNext () && i < n do
                i <- i + 1
                yield e.Current
        }
module Seq

from Microsoft.FSharp.Collections
val tryTake : n:int -> s:seq<'a> -> seq<'a>

Full name: Script.Seq.tryTake
val n : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

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

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val s : 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 e : System.Collections.Generic.IEnumerator<'a>
System.Collections.Generic.IEnumerable.GetEnumerator() : System.Collections.Generic.IEnumerator<'a>
val mutable i : int
System.Collections.IEnumerator.MoveNext() : bool
property System.Collections.Generic.IEnumerator.Current: 'a
Raw view Test code New version

More information

Link:http://fssnip.net/7WS
Posted:5 years ago
Author:Matthias Dittrich
Tags: seq