Skip to content

Commit

Permalink
Merge branch 'master' into feature/test-with-scala-3
Browse files Browse the repository at this point in the history
  • Loading branch information
winitzki authored Mar 18, 2024
2 parents 51fd24a + 6bcde47 commit 5271624
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions chapter02/worksheets/solution2.2.6.1_flatMap.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
Exercise 2.2.6.1
Implement a function fromPairs that performs the inverse
transformation to the toPairs function defined in Example 2.2.5.6.
The required type signature and a sample test are:
def fromPairs[A](xs: Seq[(A, A)]): Seq[A] = ???
scala> fromPairs(List((1,2), (3,4)))
res1: Seq[Int] = List(1, 2, 3, 4)
scala> fromPairs(List((a,b), (c,<nothing>)))
res1: Seq[(String, String)] = List("a", "b", "c", "<nothing>")
Hint: This can be done with foldLeft or with flatMap.
*/

object FromPairs {
def fromPairs[A](xs: Seq[(A, A)]): Seq[A] = {
xs.flatMap{ case (x1, x2) => List(x1, x2) }
}
def main(args: Array[String]) = {
val result: Seq[String] = fromPairs(List(("a","b"), ("c","<nothing>")))
val expected: Seq[String] = List("a", "b", "c", "<nothing>")
println("result: %s".format(result))
assert(result == expected)
val a: Seq[Int] = fromPairs(List((1, 2), (3, 4)))
val b: Seq[Int] = List(1, 2, 3, 4)
println("a: %s".format(a))
assert(a == b)
}
}

FromPairs.main(Array())

// scala> :load solution2.2.6.1_flatMap.scala
// :load solution2.2.6.1_flatMap.scala
// result: List(a, b, c, <nothing>)
// a: List(1, 2, 3, 4)
// // defined object FromPairs

0 comments on commit 5271624

Please sign in to comment.