Custom Ordering with scalaz
import java.util.regex.Pattern
import scalaz.Ordering
import scalaz._
import Scalaz._
import scala.util.matching.Regex
(Ordering.LT:Ordering) |+| (Ordering.GT:Ordering)
final case class Weather(location:String, rank:Int)
//Let's say if we want to sort by location and rank
val w1 = new Weather("USA1",2)
val w2 = new Weather("USA",1)
val w3 = new Weather("USA",5)
val w4 = new Weather("India",1)
val w5 = new Weather("India",10)
val w6 = new Weather("Zhina",3)
val w7 = new Weather("Zhina",5)
val list:List[Weather] = List(w1,w2,w3,w4,w5,w6,w7)
def weatherCompare(lhs: Weather, rhs: Weather): Boolean = {
//How do I create custom ordering?
val usaPattern:Regex = "(USA.*)".r
val res = (lhs.location, rhs.location ) match {
case (usaPattern("USA"), usaPattern("USA")) => lhs.rank cmp rhs.rank
case (usaPattern("USA"), _) => Ordering.LT
case (_,usaPattern("USA")) => Ordering.GT
case (_,_) => {
val p = (lhs.location cmp rhs.location)
val q = (lhs.rank cmp rhs.rank)
p |+| q
}
}
if(res.toInt < 1) true else false
}
//Should w1 precedence over w4?
//USA, INDIA => yes it is TRUE.
//the previous method says Ordering.LT.toInt is -1 then it s true.
weatherCompare(w1,w4)
list.sortWith( (x,y) => weatherCompare(x,y) )