如何在迭代器上循环?

时间:2017-12-19 05:20:00

标签: f# iterator

在Rust中,您可以在迭代器上循环。例如:

fn main() {
    for i in (1..4).cycle().take(5) {
        print!("{} ", i);
    }
}

输出继电器:

1 2 3 1 2 

如何在F#中做同样的事情?

[<EntryPoint>]
let main argv =
    seq { 1 .. 4 } |> (* Something *) |> Seq.take 5 |> Seq.iter (printf "%d ")
    0

1 个答案:

答案 0 :(得分:7)

我不知道任何内置函数,但您可以轻松创建自己的函数:

let cycle items = seq {
    while true do
        yield! items
}

let cycle' items =
    Seq.initInfinite (fun _ -> items) |> Seq.concat

let rec cycle'' items = seq {
    yield! items
    yield! cycle'' items
}

然后

// 1 2 3 1 2
seq { 1 .. 3 } |> cycle |> Seq.take 5 |> Seq.iter (printf "%d ")