Systematic Architecture [EN]
The blog on systems development/architecture, to be a beautiful, artistic one.
Showing posts with label
FunctionalPatterns
.
Show all posts
Showing posts with label
FunctionalPatterns
.
Show all posts
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 }) ```
Functional Patterns - zip
How to manipulate each pair of two collections. zip === Let's say two lists you have and you want to add each pair of them, like ``` 1 + 6 2 + 7 3 + 8 4 + 9 5 + 10 ``` Going on with Scala ```scala List a 1 2 3 4 5 ``` ```scala List b 6 7 8 9 10 ``` ```scala val c = a zip b ``` ```scala List c (1, 6) (2, 7) (3, 8) (4, 9) (5, 10) ``` ```scala val results = c map {case (a, b) => {a + b}} ```
Older Posts
Home
Subscribe to:
Posts (Atom)