Skip to content

Instantly share code, notes, and snippets.

@krishnanraman
Created January 15, 2013 01:11
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 krishnanraman/4535114 to your computer and use it in GitHub Desktop.
Save krishnanraman/4535114 to your computer and use it in GitHub Desktop.
Employee Monoid
case class Employee(age:Int, tenure:Int, salary:Int, name:String)
def rnd(min:Int,max:Int) = math.round(min+math.random*(max-min)).toInt
val empDB = for(employees<-1 to 10000) yield Employee( rnd(25,35),rnd(1,6),rnd(85000,150000),"emp"+employees)
case class Monoid(e:Set[Employee]) {
def plus(a:Employee,b:Employee)= {
if(a.age > b.age) a else
if(b.age > a.age) b else
if(a.tenure > b.tenure) a else
if(b.tenure > a.tenure) b else
if (a.salary > b.salary) b else
if(b.salary > a.salary) a else
if( math.random > 0.5) a else b
}
val identity = Employee(0,0,0,"id")
val theUnluckyOne = e.foldLeft(identity)((a,b)=>plus(a,b))
}
scala> empDB.sortBy(e=>(e.tenure,e.age,-e.salary)).reverse.head
res0: Employee = Employee(35,6,85079,emp7435)
scala> empDB.minBy(e=>(-e.tenure,-e.age,e.salary))
res1: Employee = Employee(35,6,85079,emp7435)
scala> Monoid(empDB.toSet).theUnluckyOne
res2: Employee = Employee(35,6,85079,emp7435)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment