diff --git a/chapter02/worksheets/solution2.2.6.3.scala b/chapter02/worksheets/solution2.2.6.3.scala new file mode 100644 index 0000000..0c61523 --- /dev/null +++ b/chapter02/worksheets/solution2.2.6.3.scala @@ -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)) diff --git a/chapter02/worksheets/solution2.2.6.4.scala b/chapter02/worksheets/solution2.2.6.4.scala new file mode 100644 index 0000000..d8fc6b1 --- /dev/null +++ b/chapter02/worksheets/solution2.2.6.4.scala @@ -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) +