0

How do I split up a collection by number of elements?

For example, if I have the following:

0,1,2,3,4,5,6,7,8

How could I partition the collection into 3 sets:

0,1,2

3,4,5

6,7,8

NOTE: F# is extremely foreign to me. So forgive my ignorance.

Here's a TicTacToe exercise that I am trying to learn F# with. In the code, I am using Seq.take and Seq.skip.

How could I write this differently?

module TicTacToe

    open FsUnit
    open NUnit.Framework

    [<Test>]
    let ``player has connected row`` () =
        let grid = Map.empty
                      .Add(0, true).Add(1, true).Add(2, true)
                      .Add(3, true).Add(4, false).Add(5, true)
                      .Add(6, true).Add(7, true).Add(8, true)

        let firstRowIsStreak = grid 
                                |> Seq.take 3
                                |> Seq.forall (fun x -> x.Value = true)

        let secondRowIsStreak = grid 
                                |> Seq.skip 3
                                |> Seq.take 3
                                |> Seq.forall (fun x -> x.Value = true)

        let thirdRowIsStreak = grid 
                                |> Seq.skip 6
                                |> Seq.take 3
                                |> Seq.forall (fun x -> x.Value = true)

        firstRowIsStreak |> should equal true 
        secondRowIsStreak |> should equal false 
        thirdRowIsStreak |> should equal true 
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • 2
    Take a look here: http://stackoverflow.com/questions/3999584/f-split-sequence-into-sub-lists-on-every-nth-element Probably the easiest is `Seq.chunkBySize` – Petr Nov 10 '15 at 12:44
  • Petr, if you post an answer using "Seq.chunkBySize" with expected output, then I will mark it as the answer. – Scott Nimrod Nov 10 '15 at 12:56

1 Answers1

1

If you have F# 4.0 you can use Seq.chunkBySize

Seq.chunkBySize 3 (seq [0;1;2;3;4;5;6;7;8])

val it : seq<int []> = seq [[|0; 1; 2|]; [|3; 4; 5|]; [|6; 7; 8|]]
Gus
  • 25,839
  • 2
  • 51
  • 76