Skip to content

Instantly share code, notes, and snippets.

@shishkin
Created October 6, 2015 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shishkin/f75e4ce355f48f3028e7 to your computer and use it in GitHub Desktop.
Save shishkin/f75e4ce355f48f3028e7 to your computer and use it in GitHub Desktop.
Example code for the Singapore scala meetup
import scala.annotation.tailrec
def sum(nums: Seq[Int]) = fold(0)(nums, _ + _)
def filterEven(nums: Seq[Int]): Seq[Int] = filter(nums, _ % 2 == 0)
def filter(nums: Seq[Int], predicate: Int => Boolean): Seq[Int] =
fold(List[Int]())(nums, (l, i) => if (predicate(i)) l :+ i else l)
def square(nums: Seq[Int]): Seq[Int] = map(nums, i => i * i)
def map(nums: Seq[Int], f: Int => Int): Seq[Int] =
fold(List[Int]())(nums, _ :+ f(_))
def fold[B](zero: B)(seq: Seq[Int], f: (B, Int) => B): B = {
var result = zero
for (i <- seq) {
result = f(result, i)
}
result
}
@tailrec
def foldRec[A, B](zero: B)(
seq: Seq[A],
f: (B, A) => B): B = {
if (seq.isEmpty) zero
else foldRec(f(zero, seq.head))(seq.tail, f)
}
val nums = 1 to 10
val evens = filterEven(nums)
val squares = square(evens)
val result = sum(squares)
println(s"Sum is $result")
def isEven: Int => Boolean = _ % 2 == 0
val result2 = nums.filter(isEven).map(i => i * i).sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment