Skip to content

Commit

Permalink
#61, Solution2.2.6.4.scala provided
Browse files Browse the repository at this point in the history
  • Loading branch information
andreas-roehler committed Apr 14, 2024
1 parent 52ef366 commit ad3b871
Showing 1 changed file with 26 additions and 0 deletions.
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 ad3b871

Please sign in to comment.