Repeating sequences in F #

I have a "compressed" stream of values ​​to which the number of events of this value is bound, for example:

let a = [ (),1; (),4; (),3;] 

I would like to "unfasten" this sequence and emit the original sequence. I could define a repeat combinator to give way! to this end

 let rec repeat avalue n = seq { if n > 0 then yield avalue; yield! repeat avalue (n-1) } let b = seq { for v,n in a do yield! repeat vn } |> Seq.toList 

Is there any way to express this inline, as a composition?

 let c = a |> Seq.XXX(fun e -> ...) 
+7
source share
3 answers

You can do this using Enumerable.Repeat :

 > Seq.collect Enumerable.Repeat [ 1, 2; 3, 4; 5, 6 ] |> List.ofSeq;; val it : int list = [1; 1; 3; 3; 3; 3; 5; 5; 5; 5; 5; 5] 
+6
source

What about

 let c = a |> Seq.collect (fun (v,i) -> [1..i] |> Seq.map (fun x -> v)) 

I do not know a library function similar to Enumerable.Repeat; if someone knows one, add a comment.

EDIT

I found a library function similar to Enumerable.Repeat, although it is in the List module:

 let c = a |> Seq.collect (fun (v,i) -> List.replicate iv) 

This would be more elegant if the pairs in the original sequence were canceled:

 let c = a |> Seq.collect ((<||) List.replicate) 

So, it seems that Enumerable.Repeat (as in the accepted answer) really makes the best decision, since its alternating argument matches the elements of the sequence:

 let c = a |> Seq.collect Enumerable.Repeat 

If anyone knows of a similar elegant solution that remains in the F # library, add a comment; thanks.

+3
source
 let rec repeat (item,n) = seq { if n > 0 then yield item; yield! repeat(item, n-1)} a |> Seq.collect repeat 

For example,

 [('a',2); ('b',2)] |> Seq.collect repeat val it: seq<char> = seq ['a';'a';'b';'b'] 
+3
source

All Articles