Skip to content

Instantly share code, notes, and snippets.

@tldeti
Last active August 29, 2015 14:24
Show Gist options
  • Save tldeti/7d40c93581d60816c522 to your computer and use it in GitHub Desktop.
Save tldeti/7d40c93581d60816c522 to your computer and use it in GitHub Desktop.
package com.gtan.turing
import akka.shapeless.HNil
import org.parboiled2._
import scala.util.Try
/**
* Created by zhang on 2015/7/14.
*/
case class Version(first:Int,second:Int,third:Int,rc:Option[Int]){
override def toString = {
first+"."+second+"."+third + rc.map("-RC"+_).getOrElse("")
}
}
object Version{
def apply(str:String): Try[Version] =
new VersionParser(str).InputLine.run()
def notZeroOr(x:Int)(f: =>Int)=
if (x != 0) {
x
} else f
implicit val VersionOrdering = new Ordering[Version] {
override def compare(x: Version, y: Version): Int = {
notZeroOr(x.first-y.first) {
notZeroOr(x.second - y.second) {
notZeroOr(x.third - y.third) {
(x.rc,y.rc) match {
case (Some(a),None) => 1
case (Some(a),Some(b)) => a-b
case (None,Some(b)) => -1
case (None,None) => 0
}
}
}
}
}
}
}
class VersionParser(val input:ParserInput) extends Parser {
def Number = rule { capture(Digits) ~> (_.toInt)}
def Digits = rule { oneOrMore(CharPredicate.Digit) }
def RC = rule { optional("-RC" ~ Number)}
def Expression:Rule1[Version] = rule {
(Number ~ '.' ~ Number ~ '.' ~ Number ~ RC) ~>
((a:Int,b:Int,c:Int,rc:Option[Int])=>Version(a,b,c,rc))
}
def InputLine = rule {Expression ~ EOI}
}
object VersionApp extends App{
def latest(versionStrs:List[String]) = {
versionStrs.flatMap(Version(_).toOption).max.toString
}
assert(latest(List("0.13.7", "0.9.10", "0.9.11-RC1")) == "0.13.7")
assert(latest(List("0.13.6", "0.13.7-RC1", "0.13.7-RC2")) == "0.13.7-RC2")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment