Most idiomatic way to write batchesOf size seq in F#

前端 未结 10 542
迷失自我
迷失自我 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:48

    My method involves converting the list to an array and recursively chunking the array:

        let batchesOf (sz:int) lt = 
            let arr = List.toArray lt
    
            let rec bite curr =
                if (curr + sz - 1 ) >= arr.Length then
                    [Array.toList arr.[ curr .. (arr.Length - 1)]]
                else
                    let curr1 = curr + sz 
                    (Array.toList (arr.[curr .. (curr + sz - 1)])) :: (bite curr1)   
    
            bite 0
    
        batchesOf 5 [1 .. 17]
    
        [[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
    

提交回复
热议问题