我在F#中有一个序列:
let n = 2
let seq1 = {
yield "a"
yield "b"
yield "c"
}
我想打印序列中的每个项目n次。我可以这样做:
let printx line t =
for i = 1 to t do
printfn "%s" line
seq1 |> Seq.iter (fun i -> printx i n)
输出是:
一个
一个
b
b
ç
c
我认为这不是最好的解决方案。如何复制序列中的项目?
答案 0 :(得分:5)
您可以创建一个函数来复制输入序列的每个元素:
let replicateAll n s = s |> Seq.collect (fun e -> Seq.init n (fun _ -> e))
然后
seq1 |> replicateAll 2 |> Seq.iter (printfn "%s")
答案 1 :(得分:3)
实际上有一个复制功能:
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]
你可以在上面做功能组合,这将摆脱lambda:
let repCol n xs = (List.replicate >> List.collect) n xs
答案 2 :(得分:3)
我宁愿选择序列计算表达式 看起来更干净:
let replicateAll n xs = seq {
for x in xs do
for _ in 1..n do
yield x
}