Skip to content

Commit

Permalink
Merge pull request #62 from andreas-roehler/master
Browse files Browse the repository at this point in the history
solution2.2.6.5 provided
  • Loading branch information
winitzki authored Apr 15, 2024
2 parents bfbe3e1 + 3868874 commit ac7763f
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions chapter02/worksheets/solution2.2.6.5.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
Exercise 2.2.6.5
Split a sequence into subsequences (“batches”) of length at most
𝑛.
The required type signature and a sample test:
def byLength[A](xs: Seq[A], maxLength: Int): Seq[Seq[A]] = ???
scala> byLength(Seq("a", "b", "c", "d"), 2)
res0: Seq[Seq[String]] = List(List(a, b), List(c, d))
scala> byLength(Seq(1, 2, 3, 4, 5, 6, 7), 3)
res1: Seq[Seq[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7))
*/

def byLength[A](xs: Seq[A], maxLength: Int): Seq[Seq[A]] = {
if (xs.length <= maxLength)
Seq(xs)
else
Seq(xs.take(maxLength)) ++ byLength(xs.drop(maxLength), maxLength)
}

val expected = Seq(Seq("a", "b"), List("c", "d"))
val result = byLength(Seq("a", "b", "c", "d"), 2)
assert(result == expected)
val a = Seq(Seq(1, 2, 3), List(4, 5, 6), List(7))
val b = byLength(Seq(1, 2, 3, 4, 5, 6, 7), 3)
assert(a == b)
val c = Seq(Seq(1, 2))
val d = byLength(Seq(1, 2), 3)
assert(c == d)


// scala> :load solution2.2.6.5.scala
// :load solution2.2.6.5.scala
// def byLength[A](xs: Seq[A], maxLength: Int): Seq[Seq[A]]
// val expected: Seq[Seq[String]] = List(List(a, b), List(c, d))
// val result: Seq[Seq[String]] = List(List(a, b), List(c, d))
// val a: Seq[Seq[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7))
// val b: Seq[Seq[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7))

0 comments on commit ac7763f

Please sign in to comment.