Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:18
Show Gist options
  • Save dacr/0923cfecf10289ed55343f9fc24151e3 to your computer and use it in GitHub Desktop.
Save dacr/0923cfecf10289ed55343f9fc24151e3 to your computer and use it in GitHub Desktop.
com-lihaoyi fastparse basic usage examples / published by https://github.com/dacr/code-examples-manager #55d6e8db-aa22-47af-b8d8-dcffaf9cd257/9f77ef93622bb59abe9df2257ddc1ff818478e19
// summary : com-lihaoyi fastparse basic usage examples
// keywords : scala, lihaoyi, fastparse, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 55d6e8db-aa22-47af-b8d8-dcffaf9cd257
// created-on : 2024-01-06T16:30:18+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "com.lihaoyi::fastparse:3.0.2"
// ---------------------
// This is largely inspired by the main example from https://com-lihaoyi.github.io/fastparse/
import fastparse._, NoWhitespace._
def number[$: P]: P[Int] = P(CharIn("0-9").rep(1).!.map(_.toInt))
def parens[$: P]: P[Int] = P("(" ~/ addSub ~ ")")
def factor[$: P]: P[Int] = P(number | parens)
def divMul[$: P]: P[Int] = P(factor ~ (CharIn("*/").! ~/ factor).rep).map(eval)
def addSub[$: P]: P[Int] = P(divMul ~ (CharIn("+\\-").! ~/ divMul).rep).map(eval)
def expr[$: P]: P[Int] = P(addSub ~ End)
def eval(tree: (Int, Seq[(String, Int)])) = {
val (base, ops) = tree
ops.foldLeft(base) { case (left, (op, right)) =>
op match {
case "+" => left + right
case "-" => left - right
case "*" => left * right
case "/" => left / right
}
}
}
val expression = "((1+1*2)+(3*4*5))/3"
val evaluation = parse(expression, expr(_))
evaluation match {
case Parsed.Success(value, _) => println(s"$expression = $value")
case Parsed.Failure(failure) => println(failure)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment