Skip to content

Instantly share code, notes, and snippets.

@kiritsuku
Created May 7, 2013 00:24
Show Gist options
  • Save kiritsuku/5529392 to your computer and use it in GitHub Desktop.
Save kiritsuku/5529392 to your computer and use it in GitHub Desktop.
parser combinator in Scala that parses floats
import scala.util.parsing.combinator.JavaTokenParsers
trait FloatParser {
private object parsers extends JavaTokenParsers {
implicit class RichElem[A <% Parser[A]](p: A) {
def <::>(q: Parser[List[A]]) = p ~ q ^^ { case m ~ n => m :: n }
}
implicit class RichListElem[A](p: Parser[List[A]]) {
def <++>(q: Parser[List[A]]) = p ~ q ^^ { case m ~ n => m ::: n }
}
implicit class RichParser[A](p: Parser[A]) {
def <::>[B <: A](q: Parser[List[B]]) = p ~ q ^^ { case m ~ n => m :: n }
}
lazy val digit = elem("digit", '0' to '9' contains _)
lazy val number = rep1(digit)
lazy val plus = '+' ~> number
lazy val minus = '-' <::> number
lazy val integer = plus | minus | number
lazy val decimal = '.' <::> number | success(Nil)
lazy val exponent = (elem('e') | elem('E')) <::> integer | success(Nil)
lazy val float = integer <++> decimal <++> exponent ^^ (_.mkString)
}
def parseFloat(in: String): Double = {
import parsers._
parseAll(float, in) match {
case Success(s, _) => s.toDouble
case NoSuccess(m, _) => sys.error(m)
}
}
}
object Test extends App with FloatParser {
println(parseFloat("1.2E-3"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment