Created
March 6, 2015 16:22
-
-
Save betandr/7b99f24796b4b2928645 to your computer and use it in GitHub Desktop.
Scala: Functional
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
| object Functional { | |
| def printItemsImperative(items: Array[String]): Unit = { | |
| var i = 0 | |
| while (i < items.length) { | |
| println(items(i)) | |
| i += 1 | |
| } | |
| } | |
| def printItemsFunctional(items: Array[String]): Unit = { | |
| for (item <- items) | |
| println(item) | |
| } | |
| def printItemsFunctionalShort(items: Array[String]): Unit = { | |
| items.foreach(println) | |
| } | |
| def printItemsPureFunctional(items: Array[String]) = { | |
| items.mkString("\n") | |
| } | |
| val items = Array("one", "two", "three") | |
| printItemsImperative(items) | |
| printItemsFunctional(items) | |
| printItemsFunctionalShort(items) | |
| println(printItemsPureFunctional(items)) | |
| // makes the pure functional method easy to test: | |
| assert(printItemsPureFunctional(items) == "one\ntwo\nthree") | |
| val lines = Array("This is a line", "and this is another line", "so's this!") | |
| val longestLine = lines.reduceLeft((a, b) => if (a.length > b.length) a else b) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment