Dávid Molnár
Dávid Molnár

Reputation: 11623

Replicate list items n times in a F# sequence

I have a sequence in F#:

let n = 2

let seq1 = {
    yield "a"
    yield "b"
    yield "c"
}

I want to print every item in the sequence n times. I can do it this way:

let printx line t = 
    for i = 1 to t do
        printfn "%s" line

seq1 |> Seq.iter (fun i -> printx i n)

Output of this is:
a
a
b
b
c
c

I think this is not the best solution. How to replicate the items in the sequence?

Upvotes: 3

Views: 1143

Answers (3)

s952163
s952163

Reputation: 6324

There is actually a replicate function:

let xs = [1; 2; 3; 4; 5]
xs |> List.collect (fun x -> List.replicate 3 x)
//val it : int list = [1; 1; 1; 2; 2; 2; 3; 3; 3; 4; 4; 4; 5; 5; 5]

And you can do function composition on it, which will get rid of the lambda:

let repCol n xs = (List.replicate >> List.collect) n xs

Upvotes: 4

Fyodor Soikin
Fyodor Soikin

Reputation: 80915

I would rather go with a sequence computation expression.
Looks cleaner:

let replicateAll n xs = seq {
  for x in xs do
    for _ in 1..n do
      yield x
}

Upvotes: 4

Lee
Lee

Reputation: 144206

You can create a function to replicate each element of an input sequence:

let replicateAll n s = s |> Seq.collect (fun e -> Seq.init n (fun _ -> e))

then

seq1 |> replicateAll 2 |> Seq.iter (printfn "%s")

Upvotes: 5

Related Questions