Most idiomatic way to write batchesOf size seq in F#

前端 未结 10 502
迷失自我
迷失自我 2020-12-16 18:42

I\'m trying to learn F# by rewriting some C# algorithms I have into idiomatic F#.

One of the first functions I\'m trying to rewrite is a batchesOf where:

         


        
10条回答
  •  时光说笑
    2020-12-16 18:53

    This version passes all my tests I could think of including ones for lazy evaluation and single sequence evaluation:

    let batchIn batchLength sequence =
        let padding = seq { for i in 1 .. batchLength -> None } 
        let wrapped = sequence |> Seq.map Some
        Seq.concat [wrapped; padding]
        |> Seq.windowed batchLength 
        |> Seq.mapi (fun i el -> (i, el)) 
        |> Seq.filter (fun t -> fst t % batchLength = 0) 
        |> Seq.map snd
        |> Seq.map (Seq.choose id)
        |> Seq.filter (fun el -> not (Seq.isEmpty el))
    

    I am still quite new to F# so if I'm missing anything - please do correct me, it will be greatly appreciated.

提交回复
热议问题