2 people like it.
Like the snippet!
Seq.filter with accumulator
Seq.filter with accumulator, without using mutable or ref.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
|
open System.Collections.Generic
let filter (acc:'a) (f:('a -> 'b -> bool * 'a)) (s:'b seq) =
let rec iter (acc:'a) (e:IEnumerator<'b>) =
match e.MoveNext() with
| false -> Seq.empty
| true -> match f acc e.Current with
| (true,newAcc) -> seq { yield e.Current; yield! iter newAcc e}
| (false,newAcc) -> seq { yield! iter newAcc e}
iter acc (s.GetEnumerator())
//Example usage
[1;2;3;4;5] |> filter 0 (fun a b -> let newA = a + 1
if newA > 3 then (true,newA)
else (false,newA))
|> Seq.iter (fun i -> printfn "%d" i)
|
namespace System
namespace System.Collections
namespace System.Collections.Generic
val filter : acc:'a -> f:('a -> 'b -> bool * 'a) -> s:seq<'b> -> seq<'b>
Full name: Script.filter
val acc : 'a
val f : ('a -> 'b -> bool * 'a)
type bool = System.Boolean
Full name: Microsoft.FSharp.Core.bool
val s : seq<'b>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>
Full name: Microsoft.FSharp.Core.Operators.seq
--------------------
type seq<'T> = IEnumerable<'T>
Full name: Microsoft.FSharp.Collections.seq<_>
val iter : ('a -> IEnumerator<'b> -> seq<'b>)
val e : IEnumerator<'b>
type IEnumerator<'T> =
member Current : 'T
Full name: System.Collections.Generic.IEnumerator<_>
System.Collections.IEnumerator.MoveNext() : bool
module Seq
from Microsoft.FSharp.Collections
val empty<'T> : seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.empty
property IEnumerator.Current: 'b
val newAcc : 'a
IEnumerable.GetEnumerator() : IEnumerator<'b>
val a : int
val b : int
val newA : int
val iter : action:('T -> unit) -> source:seq<'T> -> unit
Full name: Microsoft.FSharp.Collections.Seq.iter
val i : int
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
More information