progs/parser-combinators/comb1.sc
changeset 898 45a48c47dcca
parent 897 904de68a27a4
child 906 2bf1516d730f
equal deleted inserted replaced
897:904de68a27a4 898:45a48c47dcca
   139 println(P.parse_all("(((()()))()))"))
   139 println(P.parse_all("(((()()))()))"))
   140 println(P.parse_all(")("))
   140 println(P.parse_all(")("))
   141 println(P.parse_all("()"))
   141 println(P.parse_all("()"))
   142 
   142 
   143 // A parser for arithmetic expressions (Terms and Factors)
   143 // A parser for arithmetic expressions (Terms and Factors)
   144 {
   144 
   145 lazy val E: Parser[String, Int] = {
   145 lazy val E: Parser[String, Int] = {
   146   (T ~ p"+" ~ E).map{ case ((x, _), z) => x + z } ||
   146   (T ~ p"+" ~ E).map{ case ((x, _), z) => x + z } ||
   147   (T ~ p"-" ~ E).map{ case ((x, _), z) => x - z } || T }
   147   (T ~ p"-" ~ E).map{ case ((x, _), z) => x - z } || T }
   148 lazy val T: Parser[String, Int] = {
   148 lazy val T: Parser[String, Int] = {
   149   (F ~ p"*" ~ T).map{ case ((x, _), z) => x * z } || F }
   149   (F ~ p"*" ~ T).map{ case ((x, _), z) => x * z } || F }
   150 lazy val F: Parser[String, Int] = {
   150 lazy val F: Parser[String, Int] = {
   151   (p"(" ~ E ~ p")").map{ case ((_, y), _) => y } || NumParserInt }
   151   (p"(" ~ E ~ p")").map{ case ((_, y), _) => y } || NumParserInt }
   152 }
   152 
   153 println(E.parse_all("1+3+4"))
   153 println(E.parse_all("1+3+4"))
   154 println(E.parse("1+3+4"))
   154 println(E.parse("1+3+4"))
   155 println(E.parse_all("4*2+3"))
   155 println(E.parse_all("4*2+3"))
   156 println(E.parse_all("4*(2+3)"))
   156 println(E.parse_all("4*(2+3)"))
   157 println(E.parse_all("(4)*((2+3))"))
   157 println(E.parse_all("(4)*((2+3))"))