F# - how to group previous, this and next elements in circular Seq

Gos*_*win 4 f#

In F# How to best convert a finite Sequence-like seq [0; 1; 2; 3; 4] into a Sequence of tuples like seq [4,0,1 ; 0,1,2 ; 1,2,3 ; 2,3,4 ; 3,4,0] ?

Addition: My Seq represents circular data. In this case the vertices of a closed polyline. I need the neighboring elements to compute the angle of each corner.

Jac*_* P. 8

这是一个只使用序列的简单解决方案.请注意,如果输入和输出始终是一个列表,则会有一个稍微复杂但更快的解决方案,它只使用列表并遍历输入一次.

// Example usage: neighbors [0..4]
let neighbors input =
    let inputLength = Seq.length input
    input
    // The sequence needs to be looped three times;
    // the first and last time handle the previous value for the first
    // element in the input sequence and the next value for the last
    // element in the input sequence, respectively.
    |> Seq.replicate 3
    // Start at the previous element of the first element in the input sequence.
    |> Seq.skip (inputLength - 1)
    // Take the same number of elements as the tuple.
    |> Seq.windowed 3
    // Only keep the same number of elements as the original sequence.
    |> Seq.take inputLength
    // Convert the arrays to tuples
    |> Seq.map (fun values ->
        values.[0], values.[1], values.[2])
    // Return the result as a list of tuples.
    |> Seq.toList
Run Code Online (Sandbox Code Playgroud)