Skip to content

Commit

Permalink
Merge pull request #69 from andreas-roehler/master
Browse files Browse the repository at this point in the history
#63, solution2.2.6.3 without extra var
  • Loading branch information
winitzki authored Sep 7, 2024
2 parents 8c4be0d + 448f76b commit 9ef5b2e
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions chapter02/worksheets/solution2.2.6.3_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
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)] = {
type Acc = Seq[(A, Int)]
def init: Acc = Seq((xs.head, -1))
xs.foldLeft(init) { (x, y) => x :+ (y, x.last._2 + 1) }.tail
}

val expected: Seq[(String, Int)] = List(("a", 0), ("b", 1), ("c", 2), ("d", 3))
val result = zipWithIndex(Seq("a", "b", "c", "d"))
assert(result == expected)

0 comments on commit 9ef5b2e

Please sign in to comment.