Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Created October 24, 2013 02:27
Show Gist options
  • Select an option

  • Save kevinmeredith/7130281 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/7130281 to your computer and use it in GitHub Desktop.
Exercise from FP in Scala
// EXERCISE 9: Implement a foldMap for IndexedSeq, a common supertype
// for various data structures that provide efficient random access including Vector.
// Your implementation should use the strategy of splitting the sequence in two,/
// recursively processing each half, and then adding the answers together with the
// monoid.
def foldMapV[A,B](v: IndexedSeq[A], m: Monoid[B])(f: A => B): B = {
def go(seq: List[B], acc: B): B = seq match {
case x :: xs => go(xs, m.op(acc, x))
case Nil => acc
}
val as: List[B] = v.map(f).toList
val (a: List[B], b: List[B]) = as.splitAt(as.length / 2)
m.op(go(a, m.zero), go(b, m.zero))
}
@kevinmeredith

Copy link
Copy Markdown
Author

testing:
val seq = IndexedSeq("1","2","3","4")
val r = foldMapV(seq, intAddition)(x => x.toInt)
println(r)
assert(r == 10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment