Systematic Architecture [EN]
The blog on systems development/architecture, to be a beautiful, artistic one.
Friday, 31 July 2015
Functional Patterns - Pair Reducing
How to manipulate each pair of a collection. grouped ======= If you want to merge each two elements of a collection, like ```` 1 2 3 4 5 | v 1 + 2 3 + 4 5 ``` Going on with Scala for example use Solution I (better) 1. `grouped` 1. `map` ```scala val grouped = collection.grouped(2).toSeq val pairReduced = grouped.map(pair => {pair(0) + pair(1)}) pairReduced foreach println ``` Solution II 1. `zipWithIndex` 1. `groupBy` 1. `zip` 1. `map` ```scala val divided = collection.zipWithIndex.groupBy{case (e, i) => {(i + 1)%2}} val zipped = divided(0) zip divided(1) val pairs = zipped.map(pair => { pair._1._1 + pair._2._1 }) ```
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment