Last active
March 28, 2025 09:02
-
-
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/2f6ffbd3da7ee9fd8e4807dce4e67aaf0b7170f7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.6.4" | |
//> using dep "com.lihaoyi::fastparse:3.1.1" | |
// --------------------- | |
// 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, p => expr(using p)) | |
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