F# Split list into sublists based on comparison of adjacent elements

后端 未结 6 802
日久生厌
日久生厌 2020-12-03 17:46

I\'ve found this question on hubFS, but that handles a splitting criteria based on individual elements. I\'d like to split based on a comparison of adjacent elements, so the

6条回答
  •  醉话见心
    2020-12-03 18:34

    "adjacent" immediately makes me think of Seq.pairwise.

    let splitAt pred xs =
        if Seq.isEmpty xs then
            []
        else
            xs
            |> Seq.pairwise
            |> Seq.fold (fun (curr :: rest as lists) (i, j) -> if pred i j then [j] :: lists else (j :: curr) :: rest) [[Seq.head xs]]
            |> List.rev
            |> List.map List.rev
    

    Example:

    [1;1;2;3;3;3;2;1;2;2]
    |> splitAt (>)
    

    Gives:

    [[1; 1; 2; 3; 3; 3]; [2]; [1; 2; 2]]
    

提交回复
热议问题