3

I am attempting to make a lexer in Scala. I am attempting to do something like this

def lex(s: String): Expr = s match {
  case num(a)    => Number(a.toDouble)
  case mul(a, b) => Mul(Number(a.toDouble), Number(b.toDouble))
  case div(a, b) => Div(Number(a.toDouble), Number(b.toDouble))
  case add(a, b) => Add(Number(a.toDouble), Number(b.toDouble))
  case sub(a, b) => Sub(Number(a.toDouble), Number(b.toDouble))
  case   _       => Number(0)
}

where num, mul, div, add, sub are defined as so:

val num: Regex = "[0-9]+".r
val add: Regex = "[0-9]+\\s*\\+\\s*[0-9]+".r
val sub: Regex = "[0-9]+\\s*\\-\\s*[0-9]+".r
val div: Regex = "[0-9]+\\s*\\/\\s*[0-9]+".r
val mul: Regex = "[0-9]+\\s*\\*\\s*[0-9]+".r

When attempting to lex any expression (lex("1 + 2")) the result is always Number(0.0) instead of the expected Add(Number(1), Number(2)) Im not sure where it's going wrong...

1
  • 1
    You can use the raw interpolator to avoid having to use double back-slashes. For example: raw"[0-9]+\s*\+\s*[0-9]+".r Commented Oct 19, 2018 at 16:33

1 Answer 1

4

You need to specify which groups you want to extract.

val num = "([0-9]+)".r
val add = "([0-9]+)\\s*\\+\\s*([0-9]+)".r
val sub = "([0-9]+)\\s*\\-\\s*([0-9]+)".r
val div = "([0-9]+)\\s*\\/\\s*([0-9]+)".r
val mul = "([0-9]+)\\s*\\*\\s*([0-9]+)".r

You need one pair of parentheses per variable you extract.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.