3 people like it.
Like the snippet!
Splice sequence into other sequence
Splices a sequence into another sequence at a specified index n. Can replace the existing element at n or keep it.
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:
|
let spliceInto replace (source: 'a seq) n insert = seq {
// yield the first n - 1 elements
let i = ref 0
let enum = source.GetEnumerator()
while !i < n && enum.MoveNext() do
yield enum.Current
incr i
// skip the nth element if we're in replace mode
if replace then enum.MoveNext() |> ignore
// yield the sequence to splice in
yield! insert
// yield the rest of the original sequence
while enum.MoveNext() do yield enum.Current
}
// let xs = [1; 2; 3]
// let ys = [4; 5; 6]
//
// assert (Enumerable.SequenceEqual(spliceInto true xs 0 ys, [4; 5; 6; 2; 3]))
// assert (Enumerable.SequenceEqual(spliceInto false xs 0 ys, [4; 5; 6; 1; 2; 3]))
//
// assert (Enumerable.SequenceEqual(spliceInto true xs 1 ys, [1; 4; 5; 6; 3]))
// assert (Enumerable.SequenceEqual(spliceInto false xs 1 ys, [1; 4; 5; 6; 2; 3]))
//
// assert (Enumerable.SequenceEqual(spliceInto true xs 2 ys, [1; 2; 4; 5; 6]))
// assert (Enumerable.SequenceEqual(spliceInto false xs 2 ys, [1; 2; 4; 5; 6; 3]))
//
// assert (Enumerable.SequenceEqual(spliceInto true xs 3 ys, [1; 2; 3; 4; 5; 6]))
// assert (Enumerable.SequenceEqual(spliceInto false xs 3 ys, [1; 2; 3; 4; 5; 6]))
//
// assert (Enumerable.SequenceEqual(spliceInto true xs 4 ys, [1; 2; 3; 4; 5; 6]))
// assert (Enumerable.SequenceEqual(spliceInto false xs 4 ys, [1; 2; 3; 4; 5; 6]))
|
val spliceInto : replace:bool -> source:seq<'a> -> n:int -> insert:seq<'a> -> seq<'a>
Full name: Script.spliceInto
val replace : bool
val source : 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 n : int
val insert : seq<'a>
val i : int ref
Multiple items
val ref : value:'T -> 'T ref
Full name: Microsoft.FSharp.Core.Operators.ref
--------------------
type 'T ref = Ref<'T>
Full name: Microsoft.FSharp.Core.ref<_>
val enum : System.Collections.Generic.IEnumerator<'a>
System.Collections.Generic.IEnumerable.GetEnumerator() : System.Collections.Generic.IEnumerator<'a>
System.Collections.IEnumerator.MoveNext() : bool
property System.Collections.Generic.IEnumerator.Current: 'a
val incr : cell:int ref -> unit
Full name: Microsoft.FSharp.Core.Operators.incr
val ignore : value:'T -> unit
Full name: Microsoft.FSharp.Core.Operators.ignore
More information