Skip to content

Instantly share code, notes, and snippets.

@ferhtaydn
Created April 21, 2016 07:50
Show Gist options
  • Save ferhtaydn/442f51f91ced2115f14684dd34365df2 to your computer and use it in GitHub Desktop.
Save ferhtaydn/442f51f91ced2115f14684dd34365df2 to your computer and use it in GitHub Desktop.
simple string parser with typeclass approach
import scala.util.Try
case class Model(time: Long, value: Double)
trait StringParser[A] {
def apply(s: String): Option[A]
}
object StringParser {
def apply[A](s: String)(implicit parser: StringParser[A]): Option[A] = parser(s)
// Model is generated from a string like "123 123.0"
implicit val modelParser: StringParser[Model] = new StringParser[Model] {
override def apply(s: String): Option[Model] = s.split("\t").toList match {
case List(t, v) =>
longParser(t) match {
case Some(time) => doubleParser(v) match {
case Some(value) => Some(Model(time, value))
case None => None
}
case None => None
}
case _ => None
}
}
implicit val longParser: StringParser[Long] = new StringParser[Long] {
override def apply(s: String): Option[Long] = Try(s.toLong).toOption
}
implicit val doubleParser: StringParser[Double] = new StringParser[Double] {
override def apply(s: String): Option[Double] = Try(s.toDouble).toOption
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment