-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Andreas Roehler <andreas.roehler@online.de>
- Loading branch information
1 parent
25362d4
commit c940904
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { x => x.toList } | ||
} | ||
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 | ||
|