F#: How do i split up a sequence into a sequence of sequences

后端 未结 8 2016
执念已碎
执念已碎 2021-01-02 06:12

Background:

I have a sequence of contiguous, time-stamped data. The data-sequence has gaps in it where the data is not contiguous. I want create a

8条回答
  •  心在旅途
    2021-01-02 06:17

    You seem to want a function that has signature

    (`a -> bool) -> seq<'a> -> seq>
    

    I.e. a function and a sequence, then break up the input sequence into a sequence of sequences based on the result of the function.

    Caching the values into a collection that implements IEnumerable would likely be simplest (albeit not exactly purist, but avoiding iterating the input multiple times. It will lose much of the laziness of the input):

    let groupBy (fun: 'a -> bool) (input: seq) =
      seq {
        let cache = ref (new System.Collections.Generic.List())
        for e in input do
          (!cache).Add(e)
          if not (fun e) then
            yield !cache
            cache := new System.Collections.Generic.List()
        if cache.Length > 0 then
         yield !cache
      }
    

    An alternative implementation could pass cache collection (as seq<'a>) to the function so it can see multiple elements to chose the break points.

提交回复
热议问题