F# split sequence into sub lists on every nth element

后端 未结 8 859
时光说笑
时光说笑 2020-12-06 11:23

Say I have a sequence of 100 elements. Every 10th element I want a new list of the previous 10 elements. In this case I will end up with a list of 10 sublists.

Seq.t

相关标签:
8条回答
  • 2020-12-06 12:13

    Perhaps this simple pure implementation might be useful:

    let splitAt n xs =  (Seq.truncate n xs, if Seq.length xs < n then Seq.empty else Seq.skip n xs)
    
    let rec chunk n xs =
        if Seq.isEmpty xs then Seq.empty
        else
            let (ys,zs) = splitAt n xs
            Seq.append (Seq.singleton ys) (chunk n zs)
    

    For example:

    > chunk 10 [1..100];;
    val it : seq<seq<int>> =
      seq
        [seq [1; 2; 3; 4; ...]; seq [11; 12; 13; 14; ...]; 
         seq [21; 22; 23; 24; ...]; seq [31; 32; 33; 34; ...]; ...]
    
    > chunk 5 [1..12];;
    val it : seq<seq<int>> =
      seq [seq [1; 2; 3; 4; ...]; seq [6; 7; 8; 9; ...]; seq [11; 12]]
    
    0 讨论(0)
  • 2020-12-06 12:13

    I found this to be easily the fastest:

    let windowChunk n xs =
        let range = [0 .. Seq.length xs]
        Seq.windowed n xs |> Seq.zip range 
                          |> Seq.filter (fun d -> (fst d) % n = 0)
                          |> Seq.map(fun x -> (snd x))
    

    i.e. window the list, zip with a list of integers, remove all the overlapping elements, and then drop the integer portion of the tuple.

    0 讨论(0)
提交回复
热议问题