https://github.com/mthaler/arithmetic-expression-parser
Simple arithmetic expression parser written in Kotlin
https://github.com/mthaler/arithmetic-expression-parser
arithmetic arithmetic-expression-parser kotlin kotlin-library parser parser-combinators parsers
Last synced: 10 months ago
JSON representation
Simple arithmetic expression parser written in Kotlin
- Host: GitHub
- URL: https://github.com/mthaler/arithmetic-expression-parser
- Owner: mthaler
- License: apache-2.0
- Created: 2020-12-24T06:51:04.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2023-11-22T11:49:26.000Z (over 2 years ago)
- Last Synced: 2025-02-15T09:44:19.391Z (over 1 year ago)
- Topics: arithmetic, arithmetic-expression-parser, kotlin, kotlin-library, parser, parser-combinators, parsers
- Language: Kotlin
- Homepage:
- Size: 157 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# arithmetic-expression-parser
[](https://maven-badges.herokuapp.com/maven-central/com.mthaler/aparser)
**arithmetic-expression-parser** is a simple arithmetic expression parser written in Kotlin. It supports the following operations:
- unary: -
- binary: +, -, *, /, ^ (power), % (modulo)
- functions: abs, acos, asin, atan, cos, cosh, exp, ln, log, sin, sinh, sqrt, tan, tanh
For trigonometric functions, both radians and degrees are supported.
# Design
The parser is build using combinators. Parsing is a two-step process:
- the tokens package provides various token parsers that match certain tokens, e.g. char literals, identifiers, numbers etc.
- arithmetic package defines expression parsers that use the token parsers to create parsers for arithmetic expressions.
# Usage
The `Expression` object parses arithmetic expressions:
```kotlin
Expression("3 + 4")
```
This will return an abstract syntax tree. The `tryEval` extension method can be used to evaluate the expression:
```kotlin
Expression("3 + 4").tryEval()
```
The result will be `Success(7.0)`. If an invalid expression like `Expression("foo(0)")` is evaluated, a `Failure` will be returned.
## Trigonometric units
The default trigonometric unit is radians, but degrees are also supported:
```kotlin
val ctx = Context.Empty.copy(trigonometricUnit = TrigonometricUnit.Degree)
Expression("sin(90)").tryEval(ctx)
```
The result will be `Success(1.0)`.
## Global variables
Global variables can be defined using upper case letters:
```kotlin
val ctx = Context(TrigonometricUnit.Rad, mapOf(Pair("A", 2.0)))
Expression("A + 3").tryEval(ctx)
```
The result will be `Success(5.0)`.
# License
Apache-2.0 License