2

I'm currently writing a bit of F#. I've created a method that is the equivalent of Ruby's Enumerable#each_slice method and was wondering if somebody has a better (i.e. more elegant, more concise, more readable) solution.

Here it is:

let rec slicesBySize size list =
    match list with
    | [] -> [] // case needed for type inference
    | list when list.Length < size -> [list]
    | _ ->
        let first = list |> Seq.take size |> List.ofSeq
        let rest = list |> Seq.skip size |> List.ofSeq

        [first] @ slicesBySize size rest

Thanks for any and all feedback/help.

Kurt Mueller
  • 3,173
  • 2
  • 29
  • 50
  • Seems to be similar to this question: http://stackoverflow.com/questions/8064016/how-to-partition-a-list-with-a-given-group-size – Ringil Mar 02 '16 at 18:41

1 Answers1

3

You're looking for List.chunkBySize, which was added in F# 4.0. There are also Seq and Array variants.

Daniel
  • 47,404
  • 11
  • 101
  • 179
  • I was looking at the F# docs and can't find where I specify the version of F# I want to use: https://msdn.microsoft.com/en-us/library/ee353738.aspx I'm going to guess this is for F# 3.0 but I just can't find where I can specify F# 4.0 – Kurt Mueller Mar 03 '16 at 00:33
  • Yes, it appears MSDN hasn't been updated for F# 4.0 (thus my link to the source code). – Daniel Mar 03 '16 at 15:01