2 people like it.
Like the snippet!
Collapse a sequence
Eliminate repetitions in a sequence, preserving the first element in each run of repeats.
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:
32:
33:
34:
35:
36:
37:
38:
39:
40:
|
module Seq =
let inline collapseBy f s =
seq {
let mutable prev = None
for x in s do
match prev with
| None ->
yield x
| Some p when f p x ->
yield x
| _ ->
()
prev <- Some x
}
let inline collapse s =
s |> collapseBy (<>)
module Demo =
[ 1; 2; 2; 3; 1; 2; 2; 2 ]
|> Seq.collapse
|> Seq.iter (printfn "%A")
Seq.empty<int>
|> Seq.collapse
|> Seq.iter (printfn "%A")
[ "a" ] |> Seq.collapse
|> Seq.iter (printfn "%A")
type LatLon = { Lat : float; Lon : float }
[ { Lat = 0.1; Lon = 1.2 }
{ Lat = 0.1; Lon = 1.3 }
{ Lat = 0.2; Lon = 1.2 }
{ Lat = 0.1; Lon = 1.2 } ]
|> Seq.collapseBy (fun ll1 ll2 -> ll1.Lat <> ll2.Lat)
|> Seq.iter (printfn "%A")
|
module Seq
from Microsoft.FSharp.Collections
val collapseBy : f:('a -> 'a -> bool) -> s:seq<'a> -> seq<'a>
Full name: Script.Seq.collapseBy
val f : ('a -> 'a -> bool)
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 mutable prev : 'a option
union case Option.None: Option<'T>
val x : 'a
union case Option.Some: Value: 'T -> Option<'T>
val p : 'a
val collapse : s:seq<'a> -> seq<'a> (requires equality)
Full name: Script.Seq.collapse
val s : seq<'a> (requires equality)
module Demo
from Script
Multiple items
module Seq
from Script
--------------------
module Seq
from Microsoft.FSharp.Collections
val iter : action:('T -> unit) -> source:seq<'T> -> unit
Full name: Microsoft.FSharp.Collections.Seq.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val empty<'T> : seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.empty
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<_>
type LatLon =
{Lat: float;
Lon: float;}
Full name: Script.Demo.LatLon
LatLon.Lat: float
Multiple items
val float : value:'T -> float (requires member op_Explicit)
Full name: Microsoft.FSharp.Core.Operators.float
--------------------
type float = System.Double
Full name: Microsoft.FSharp.Core.float
--------------------
type float<'Measure> = float
Full name: Microsoft.FSharp.Core.float<_>
LatLon.Lon: float
val ll1 : LatLon
val ll2 : LatLon
More information