2 people like it.
Like the snippet!
Continue sequence after applying Seq.takeWhile, skip, take, etc
Sometimes you need to take more elements from a sequence, e.g. look at https://stackoverflow.com/questions/12562327/how-to-do-seq-takewhile-one-item-in-f
This solution allows fetching elements from the same sequence after applying takeWhile, skip, take and other sequence functions.
However, need to remember to call function with right parameter: use 'true' to include current element into result sequence (after takeWhile for example)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
|
/// allows fetching elements from same sequence
type ContinueSequence<'a> (xs: 'a seq) =
let en = xs.GetEnumerator()
member _.Continue (includeCurrent: bool) =
let s = seq { while en.MoveNext() do yield en.Current }
let c = seq { en.Current }
if includeCurrent then
Seq.append c s
else
s
interface IDisposable with
member _.Dispose() =
en.Dispose()
/// usage example:
let a = seq [1; 2; 3; 4; 5; 6; 7]
use seq = new ContinueSequence<_>(a)
let s1 = seq.Continue(false) |> Seq.takeWhile((>) 3) // take 1 and 2, 3 is current
let s2 = seq.Continue(true) |> Seq.take(2) // take 3 and 4
let s3 = seq.Continue(false) |> Seq.skip(1) // skip 5
let s =
s1
|> Seq.append <| s2
|> Seq.append <| s3
|> Seq.toList
// s = [1; 2; 3; 4; 6; 7]
|
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<_>
type bool = System.Boolean
Full name: Microsoft.FSharp.Core.bool
module Seq
from Microsoft.FSharp.Collections
val append : source1:seq<'T> -> source2:seq<'T> -> seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.append
val takeWhile : predicate:('T -> bool) -> source:seq<'T> -> seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.takeWhile
val take : count:int -> source:seq<'T> -> seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.take
val skip : count:int -> source:seq<'T> -> seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.skip
val toList : source:seq<'T> -> 'T list
Full name: Microsoft.FSharp.Collections.Seq.toList
More information