Created
October 24, 2013 02:27
-
-
Save kevinmeredith/7130281 to your computer and use it in GitHub Desktop.
Exercise from FP in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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)) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
testing:
val seq = IndexedSeq("1","2","3","4")
val r = foldMapV(seq, intAddition)(x => x.toInt)
println(r)
assert(r == 10)