Skip to content

Instantly share code, notes, and snippets.

@betandr
Created March 6, 2015 16:22
Show Gist options
  • Select an option

  • Save betandr/7b99f24796b4b2928645 to your computer and use it in GitHub Desktop.

Select an option

Save betandr/7b99f24796b4b2928645 to your computer and use it in GitHub Desktop.
Scala: Functional
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