Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution2.2.6.5 provided #62

Merged
merged 5 commits into from
Apr 15, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions chapter02/worksheets/solution2.2.6.5.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
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 then
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are using both Scala 2 and Scala 3 for the tests. The syntax if a then b else c is supported only in Scala 3.

I suggest rewriting to the old and compatible syntax if (xs.legth <= maxLength) Seq(xs) else Seq(...).

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)
andreas-roehler marked this conversation as resolved.
Show resolved Hide resolved

// 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))

Loading