-
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.
Merge pull request #60 from andreas-roehler/master
solution2.2.6.3 provided
- Loading branch information
Showing
2 changed files
with
51 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,25 @@ | ||
/** | ||
Exercise 2.2.6.3 | ||
Use foldLeft to implement the zipWithIndex method for sequences. | ||
The required type signature and a sample test: | ||
def zipWithIndex[A](xs: Seq[A]): Seq[(A, Int)] = ??? | ||
scala> zipWithIndex(Seq("a", "b", "c", "d")) | ||
res0: Seq[(String, Int)] = List((a, 0), (b, 1), (c, 2), (d, 3)) | ||
*/ | ||
|
||
def zipWithIndex[A](xs: Seq[A]): Seq[(A, Int)] = { | ||
val a = (0 to xs.length - 1) | ||
type Acc = Seq[(A, Int)] | ||
var counter = (-1) | ||
def init: Acc = Seq.empty | ||
xs.foldLeft(init) { (x, y) => (counter = counter + 1); (x :+ (y, counter)) } | ||
} | ||
|
||
// scala> :load solution2.2.6.3.scala | ||
// :load solution2.2.6.3.scala | ||
// def zipWithIndex[A](xs: Seq[A]): Seq[(A, Int)] | ||
// val result: Seq[(String, Int)] = List((a,0), (b,1), (c,2), (d,3)) | ||
// val expected: Seq[(String, Int)] = List((a,0), (b,1), (c,2), (d,3)) |
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,26 @@ | ||
/** | ||
Exercise 2.2.6.4 | ||
Use foldLeft to implement a function filterMap that combines map and | ||
filter for sequences. The predicate is applied to the elements of | ||
the initial sequence, and values that pass the predicate are mapped. | ||
The required type signature and a sample test: | ||
def filterMap[A, B](xs: Seq[A])(pred: A => Boolean)(f: A => B): Seq[B] = ??? | ||
scala> filterMap(Seq(1, 2, 3, 4)) { x => x > 2 } { x => x * 10 } | ||
res0: Seq[Int] = List(30, 40) | ||
*/ | ||
|
||
def filterMap[A, B](xs: Seq[A])(pred: A => Boolean)(f: A => B): Seq[B] = { | ||
xs.filter(pred).map(f) | ||
} | ||
|
||
val result = filterMap(Seq(1, 2, 3, 4)) { x => x > 2 } { x => x * 10 } | ||
val expected: Seq[Int] = List(30, 40) | ||
assert(result == expected) | ||
|
||
// scala> filterMap(Seq(1, 2, 3, 4)) { x => x > 2 } { x => x * 10 } | ||
// filterMap(Seq(1, 2, 3, 4)) { x => x > 2 } { x => x * 10 } | ||
// val res1: Seq[Int] = List(30, 40) | ||
|