Skip to content

Instantly share code, notes, and snippets.

@mikewadhera
Created April 2, 2011 22:24
Show Gist options
  • Save mikewadhera/899964 to your computer and use it in GitHub Desktop.
Save mikewadhera/899964 to your computer and use it in GitHub Desktop.
// Abstract Types and for loop
object Iterables {
def filter[T](all: Iterable[T], predicate: T => Boolean) : Iterable[T] = {
for {
t <- all;
if predicate(t)
} yield t
}
def find[T](all: Iterable[T], predicate: T => Boolean) : T = {
filter(all, predicate).first
}
}
// Higher Order functions
object Predicates {
def or[T](f1: T => Boolean, f2: T => Boolean) = (t: T) => f1(t) || f2(t)
def and[T](f1: T => Boolean, f2: T => Boolean) = (t: T) => f1(t) && f2(t)
def notNull[T] : T => Boolean = _ != null
}
// Side-effect free quicksort using pattern matching
object Sorters {
def qsort[T <% Ordered[T]](list: List[T]) : List[T] = list match {
case Nil => Nil
case x::xs =>
val (before,after) = xs partition( _ < x )
qsort(before) ++ (x :: qsort(after))
}
}
// Thread-safe mutable and immutable implementations
trait Service[Key, Value] {
def lookup(k: Key) : Option[Value]
def insert(k: Key, v: Value) : Unit
}
import collection.mutable.{HashMap => MutableHashMap};
class MutableService[Key, Value] extends Service[Key, Value] {
val currentIndex = new MutableHashMap[Key, Value]
def lookup(k: Key) : Option[Value] = {
synchronized(currentIndex.get(k))
}
def insert(k: Key, v: Value) {
synchronized {
currentIndex.put(k,v)
}
}
}
import collection.immutable.{HashMap => ImmutableHashMap}
class ImmutableService[Key, Value] extends Service[Key, Value] {
var currentIndex = new ImmutableHashMap[Key, Value]
def lookup(k: Key) : Option[Value] = {
currentIndex.get(k)
}
def insert(k: Key, v: Value) {
synchronized {
currentIndex = currentIndex + ((k,v))
}
}
}
object MyApplication {
def main(args : Array[String]) : Unit = {
import Iterables._
val list = List(1,2,3,4,5,6)
val isEven = (x: Int) => x % 2 == 0
println(filter(list, isEven)) // List(2,4,6)
println(find(list, isEven)) // 2
import Predicates._
val notEmpty = (word: String) => notNull(word) && word.length > 0
val palindrome = (word: String) => word == word.reverse
val raceCarIsPalindrome = and(notEmpty, palindrome)("racecar")
println(raceCarIsPalindrome); // true
import Sorters._
println(qsort(List(5,4,3,7))) // List(3,4,5,7)
val mutableService = new MutableService[String, String]
mutableService.insert("Greeting", "Hello")
println(mutableService.lookup("Greeting").getOrElse("Not Found")) // Hello
val immutableService = new ImmutableService[String, String]
immutableService.insert("Greeting", "Hello")
println(immutableService.lookup("Greeting").getOrElse("Not Found")) // Hello
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment