Skip to content

Commit

Permalink
Merge pull request #60 from andreas-roehler/master
Browse files Browse the repository at this point in the history
solution2.2.6.3 provided
  • Loading branch information
winitzki authored Apr 14, 2024
2 parents 5aa0c11 + d03d9e5 commit bfbe3e1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
25 changes: 25 additions & 0 deletions chapter02/worksheets/solution2.2.6.3.scala
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))
26 changes: 26 additions & 0 deletions chapter02/worksheets/solution2.2.6.4.scala
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)

0 comments on commit bfbe3e1

Please sign in to comment.