与您的最后一个问题一样,没有库函数可以做到这一点。最直接的解决方案是使用IEnumerator
. 但是,您可以编写一个更普遍有用的函数(然后也可以用于其他目的)。
module Seq =
/// Iterates over elements of the input sequence and groups adjacent elements.
/// A new group is started when the specified predicate holds about the element
/// of the sequence (and at the beginning of the iteration).
/// For example:
/// Seq.groupWhen isOdd [3;3;2;4;1;2] = seq [[3]; [3; 2; 4]; [1; 2]]
let groupWhen f (input:seq<_>) = seq {
use en = input.GetEnumerator()
let running = ref true
// Generate a group starting with the current element. Stops generating
// when it founds element such that 'f en.Current' is 'true'
let rec group() =
[ yield en.Current
if en.MoveNext() then
if not (f en.Current) then yield! group()
else running := false ]
if en.MoveNext() then
// While there are still elements, start a new group
while running.Value do
yield group() }
为了解决最初的问题,您可以检查序列的第一个元素是否是 1 以外的数字。您将获得一个组序列,其中一个组是序列序列 - 然后您可以连接这些组:
items
|> Seq.groupWhen (fun s -> Seq.head s <> 1)
|> Seq.map Seq.concat
编辑:我还在此处将函数作为片段发布(带有漂亮的 F# 格式):http: //fssnip.net/6A